AngularJS Integration with Spring MVC for File Upload

After completing the AngularJS part of the file upload, I encountered an error when trying to send the uploaded file to my controller. The error message indicated that the URL was not valid:

The code for my controller is as follows:

@RestController
@RequestMapping("/files")
public class UploadController {
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @Produces(MediaType.APPLICATION_JSON) 
    public Data continueFileUpload(HttpServletRequest request, HttpServletResponse response){
            MultipartHttpServletRequest mRequest;

....

}

Below is the AngularJS service that links to the controller:

AngularJS controller function snippet:

$scope.uploadFile = function() {
    var file = $scope.myFile;
    console.log('file is ');
    console.dir(file);

    var uploadUrl = "/fileUpload";  /* At this point, I needed to determine the correct URL to set */
    FileUploadService.uploadFileToUrl(file, uploadUrl).then(
        function(result) {
            $scope.errors = FileUploadService.getResponse();
            console.log($scope.errors);
            $scope.errVisibility = true;
        }, function(error) {
            alert('error');
        })

}

The corresponding FileUploadService script in JS:

myapp.service('FileUploadService', [ '$q', '$http', function($q, $http) {
    var deffered = $q.defer();
    var responseData;
    this.uploadFileToUrl = function(file, uploadUrl) {
        var fd = new FormData();
        fd.append('file', file);
        return $http.post(uploadUrl, fd, {
            transformRequest : angular.identity,
            headers : {
                'Content-Type' : undefined
            }
        }).success(function(response) {

            /* $scope.errors = response.data.value; */
            console.log(response);
            responseData = response;
            deffered.resolve(response);
            return deffered.promise;
        }).error(function(error) {
            deffered.reject(error);
            return deffered.promise;
        });

    }

    this.getResponse = function() {
        return responseData;
    }

} ]);

I am uncertain about which specific URl I should provide to call the continueFileUpload function.

Here is an updated insight:

Screenshot Link

The aforementioned itr appears to be loaded without any content.

The directive I utilized is as follows:

Directive Image

Here is a glimpse at the HTML structure used:

HTML Structure Picture

Answer №1

Experiment with this: let uploadLink = "/files/fileUpload";

Answer №2

Here is a way to approach it:

Create a Maven web project

var uploadUrl = "./fileUpload";

Alternatively, in a normal web project

var uploadUrl = "../fileUpload";

You can also directly call using this format:

http://yourip:portnumber/projectName/controllerName;

Hopefully, this method will work smoothly for you.

Answer №3

Below is the complete solution that works:

The Controller (controller.java):

@RestController
@RequestMapping("/api")
public class FileController {
    @RequestMapping(value = "/getFile", method = RequestMethod.POST)
        public ResponseEntity<byte[]> getFileForm(@RequestParam(value = "file") MultipartFile multipartFile)
                throws IOException {

            // code ............
            return null;

        }}

Angular.Js Code:

$scope.downloadFile = function(){

              var a = document.createElement("a");
              document.body.appendChild(a);
              var fileExt = $scope.file.name.substring($scope.file.name.lastIndexOf('.')+1, $scope.file.namee.length) || $scope.file.name;

             var fileType = FileService.GenerateFileType(fileExt);

              FileService.getFile($scope.file).success(function(data){

                    var file = new Blob([data], {type:fileType});
                    var fileURL = window.URL.createObjectURL(file);
                    a.href = fileURL;
                    a.download = $scope.file.name;
                    a.click();


                });
}

Service for Files (FileService.js):

var GenerateFileType = function (fileExtension) {  
    var FileType = null;    
    switch (fileExtension.toLowerCase()) {  
            case "doc":  
            case "docx":  
                FileType = "application/msword";  
                break;  
            case "xls":  
            case "xlsx":  
                FileType = "application/vnd.ms-excel";  
                break;  
            case "pps":  
            case "ppt":
            case "pptx":
                FileType = "application/vnd.ms-powerpoint";  
                break;  
            case "txt":  
            case "properties":
                FileType = "text/plain";  
                break;  
            case "rtf":  
                FileType = "application/rtf";  
                break;  
            case "pdf":  
                FileType = "application/pdf";  
                break;  
            case "msg":  
            case "eml":  
                FileType = "application/vnd.ms-outlook";  
                break;  
            case "gif":  
            case "bmp":  
            case "png":  
            case "jpg":  
                FileType = "image/JPEG";  
                break;  
            case "dwg":  
                FileType = "application/acad";  
                break;  
            case "zip":  
                FileType = "application/x-zip-compressed";  
                break;  
            case "rar":  
                FileType = "application/x-rar-compressed";  
                break;  
        }  
    return FileType;
    }  

Also,

 var getFile = function(fileObj){

              return    $http({
                  method: 'POST',
                  url: "api/getFile",

                  headers: { 'Content-Type': undefined },

                  transformRequest: function (data) {
                      var fd = new FormData();
                      fd.append("file", data.file);

                    return fd;
                  },

                  data: {file: fileObj }
                });
             }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving the extraction of a particular string from an HTML element using JavaScript

<input id="WD01B3" ct="CB" lsdata="{2:'WD01B4',4:'Any',20:'\x7b\x22WDA_TYPE\x22\x3a\x22DROPDOWN_BY_KEY\x22,\x22WDA_ID\x22\x3a\x22ABCA950297D2C0C432BAB9BB ...

The code provided creates a web form using HTML and ExpressJS to store submitted information into a MongoDB database. However, there seems to be an issue with the 'post' method, while the 'get' method functions correctly

When I try to submit entries (name, email, address) on localhost:3000 in the browser, the 'post' function is not creating an object in the mongo database even though it works from the postman. The browser displays an error message saying "unable ...

Pointcut expression for a custom annotation in a subclass using Spring AOP

I am currently developing a logging feature that requires me to intercept all classes and methods annotated with a custom annotation. Here is the code for the custom annotation that can be applied to classes and methods: @Documented @Inherited @Retention ...

Navigating in React Navigation: Techniques to Directly Access a Specific Index in a Datasource

I am a beginner at React Native and I have been working on developing a simple recipe app. Everything was going well until I reached the point where I needed to navigate to a specific recipe from my dataset. I am looking to create a singleRecipe.js compone ...

The template literal expression is being flagged as an "Invalid type" because it includes both string and undefined values, despite my cautious use of

I am facing an issue with a simple component that loops out buttons. During the TypeScript build, I encountered an error when calling this loop: 17:60 Error: Invalid type "string | undefined" of template literal expression. In my JSX return, I ...

Guide to refreshing the modal component with updated properties

In my application, I have created a modal component for managing recipes. This modal allows users to save recipes to a list. let modal = <Modal saveRecipe={this.saveRecipe} closeModal={this.toggleModal}/> However, I also want to utilize the same m ...

What is the proper way to incorporate target=blank using JavaScript?

Snapshot: https://i.sstatic.net/XWk8x.png (reference: freenetph.yn.lt) I stumbled upon this code for random links on a third-party website (can't remember the name) and it seems really useful to me. However, I'm facing an issue where I want a ...

Extracting information from WordPress JSON API using Ionic

Using JSON API, I am able to fetch data from WordPress in Ionic. However, I am facing an issue where only 10 data points are being retrieved at a time from the WordPress JSON API. What is the best way to fetch the next set of 10 posts with an on-screen lo ...

"Implementing a feature in AngularJS to dynamically display markers on a Google Map based on latitude and

I am a newcomer to AngularJS and I am attempting to pass my JSON latitude and longitude based on ID into the Google API. Here is the structure of my JSON file: { "totalCount":206, "deals":[{ "id":"2", "Name":"samir", "locations":[{ ...

Using jQuery to add the name of a file to FormData and fetching it in a PHP script

I've been working on a JS code snippet dedicated to uploading images based on their file paths: var data = new FormData(); data.append('fileName', fileName); data.append('file', file); $.ajax({ url : dbPath + "upload-file.php" ...

Click on a button to completely remove all JavaScript from your website using jQuery

I'm currently experiencing some difficulties with my website Concept Studio. On a specific page, I have a typing animation within a form and I'd like to include a button that allows users to skip the animation. However, I'm unsure of how to ...

The ngRoute feature seems to be malfunctioning and unable to switch views when an <a> tag is clicked

Just starting out with Angular JS and encountering an issue that has me stumped. Would really appreciate some help in resolving it. In my project, I have an index file connected to app.js which utilizes ngRoute. See the code snippet below for reference: ...

Issue with the Layout of Android Ads

Can someone help me with adding AdMob banner to my Android application? I've tried various methods but can't seem to get it to display at the bottom of my layout. Below is the code snippet from my Activity. Please review and let me know what migh ...

Pass data from controller using Ajax in CodeIgniter

Here is my JavaScript code: $(document).ready(function(){ $("input[type='checkbox']").change(function(){ var menu_id = this.value; if(this.checked) var statusvalue = "On"; else var statusvalue = "Off"; $.ajax( ...

Activate the function on the open window

I am looking to open a new window that contains a list of objects which need to be filtered based on a selection made in a previous window. I understand that I can filter the list using a function, but I am unsure of how to actually run this function. Her ...

Incorporate a distinct, unique value from a JSON dataset into each iteration of the .each statement

My code includes an each statement that looks like this: $.each(data, function(i, value) { sublayers.push({ sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "=&ap ...

Combining and consolidating JSON attributes

I am working with a JSON object that has multiple instances of the email property, like so: accounts": [ { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61120e0c04030e051821050e0c">[email protected]</a& ...

Android webview encounters issues with loading javascript and css files

I am facing an issue with my Angular web app that I want to run locally inside a WebView of my android app. However, upon opening the app, all I see is a blank screen. Upon inspecting the chrome tool, I noticed a net::ERR_FILE_NOT_FOUND error for the .js ...

Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality. While researching, I came across a resource on how to vali ...

Download attachments using Django from a web browser

Trying to send an image as an attachment. This is the code I am using: resp = FileResponse(open(fullImgPath, "rb")) resp['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path. basename(fullImgPath)) resp["Content-Type"]= ...