How can you configure the request section for a POST request using angular-file-upload and Spring?

Regrettably, the solution provided in this answer does not resolve my issue. It seems that the request parameter file is missing from my POST request for some unknown reason.

I am attempting to upload any type of file, be it binary or text, using a POST request. The REST controller implementation looks like this:

@PostMapping(WordEmbeddingApiPaths.UPLOAD_MODEL)
@RequestMapping(method=RequestMethod.POST, headers={"Content-Type=multipart/form-data"})
public ResponseEntity<WordVectorListDto> uploadModel(
        @RequestParam("file") MultipartFile file, 
        RedirectAttributes redirectAttributes) {

    LOGGER.debug("POST uploadModel");

    return new ResponseEntity<WordVectorListDto>((WordVectorListDto)null, HttpStatus.OK); 
}

On the client side, I have the following code running:

var uploader = $scope.uploader = new FileUploader({
    url: 'http://localhost:8080/rest-api/dl4j/we/uploadModel'
});

uploader.onAfterAddingFile = function($modelFile) {
    console.info('onAfterAddingFile', $modelFile);

    var fd = new FormData();

    fd.append('file', $modelFile.file);

    $http.post($modelFile.url, fd, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }, 
        params: {'file' : $modelFile.file}
    })
    .then(
        function (data) {
            alert("upload success");
        }, 
        function (data, status) {
            alert("upload error");
        }
     );

};

Despite this, I am receiving a 400 Bad Request response from the server.

Any insights on what might be causing this problem?


Update:

An internal exception was thrown on the server side, indicating:

org.springframework.web.multipart.support.MissingServletRequestPartException
: Required request part 'file' is not present

It appears that I am already setting this - how can I rectify this situation?

Answer №1

Exploring AngularJS FormData Posting

When utilizing a POST request with an FormData API object in AngularJS, it is crucial to pay attention to the Content-Type header and set it to undefined.

var fd = new FormData();
fd.append('file', $modelFile.file);

$http.post($modelFile.url, fd, {
    headers: {
        //'Content-Type': 'multipart/form-data'
        'Content-Type': undefined
    }, 
    //params: {'file' : $modelFile.file}
})

When sending a FormData object using the XHR send() method, the content type automatically defaults to multipart/form-data along with the necessary boundary.

Overriding the content type in AngularJS may lead to issues with setting the proper boundary for the request.


Effective Debugging of Code

This scenario highlights the importance of debugging each component individually rather than piecing them all together at once.

There are several unknowns present:

  • An untested AngularJS POST method
  • An unchecked Spring Backend functionality
  • A mysterious AngularJS service without thorough testing

While errors in the POST method have been identified, other uncertainties remain. Are the backend functionalities functioning correctly? Is the FileUploader service implemented properly?

Debugging requires isolating variables and conducting separate evaluations.

Try validating the Angular POST method against a reliable backend like HTTP BIN - HTTP Request & Response Service.

Ensure the Spring backend functions as expected with tested uploaders.

For further insights on effective debugging techniques, refer to How to debug small programs.

Answer №2

When utilizing @EnableAutoConfiguration, it is important to follow these steps outlined in this discussion https://github.com/spring-projects/spring-boot/issues/2958

  1. @EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
  2. To configure the necessary beans:

    @Bean(name = "multipartResolver") public CommonsMultipartResolver commonsMultipartResolver(){ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(50*1024*1024); return resolver ; }

    @Bean @Order(0) public MultipartFilter multipartFilter(){ MultipartFilter multipartFilter = new MultipartFilter(); multipartFilter.setMultipartResolverBeanName("multipartResolver"); return multipartFilter; }

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

What are the reasons for deprecating bindToController in Typescript?

When I am creating an AngularJS directive using TypeScript, I typically use the bindToController property to bind parameters to the controller for easy access. export class MyDirective implements IDirective { controller = MyController; controllerA ...

Unable to retrieve any data while consuming a RESTful web service with AngularJS

As a novice in Angularjs, I am seeking assistance with examples for the following: The added script is as follows: var app = angular.module('myapp', []); app.controller('MyCtrl1', ['$scope', 'UserFactory', functio ...

What is the best way to display the friends of the current user in a MeanJS application?

How can I show the Authenticated user's friends on an angularjs page? // Retrieve the list of Friends $scope.find = function() { $scope.friends = Authentication.user.friends; $scope.firstFriendName = Authentication.user.friends; ...

What is the best way to check the validity of an if statement within JavaScript or AngularJS?

Here is a snippet of code that I have: $scope.changePassword = function () { sessionService.save($scope.sessionData); if(sessionService.account.newPassword == sessionService.account.currentPassword) { ...

Changing a file object into an image object in AngularJS

Can a file object be converted to an image object? I am in need of the width and height from the file (which is an image). Here is my code: view: <button id="image_file" class="md-button md-raised md-primary" type="file" ngf-select="uploadFile($file ...

Navigating Spinners in Protractor: A step-by-step guide

When I'm working on my AngularJS application, I've noticed that when a page loads, two things happen concurrently: the content of the page loads and back-end resources start loading. A spinner appears while the back-end resources are still loadin ...

Bring in a template in TypeScript with no need for require statement

Currently, I'm utilizing TypeScript along with Angular 1.5 component. In my scenario, I have a custom decorator in place through which I send templates via require function. The setup is functional; however, I am consistently receiving a tslint warnin ...

Arranging information in an AngularJS table based on column headers

I have been developing a web application using AngularJS. The application sends an HTTP request to a database server to retrieve information about claims, which is then displayed in a table. Each page of the table shows 100 claims, with a total of approxim ...

Storing repeated inputs in local storage multiple times

I am working on a feature where I need to store data in local storage multiple times using a dropdown menu and some input fields. Currently, I am able to retrieve all the values from the input fields and see them in the console log. My goal is to save thes ...

Is it possible for an angular directive to transmit arguments to functions within specified expressions in the directive's attributes?

I am working on a form directive that utilizes a specific callback attribute with an isolate scope: scope: { callback: '&' } This directive is placed within an ng-repeat, where the expression passed in includes the id of the object as an ar ...

Error in Angular2: "Promise" name not found despite successful installation of global dependencies

I'm currently developing an application using Angular 2 and Node.js. I've already installed all the necessary dependencies specified in package.json. Inside this file, there is a postinstall command that should install the required dependencies m ...

Is the input disabled when clicked on?

To ensure the end-to-end functionality of my application, I have implemented a scenario where upon clicking a spinner button, both Username and Password input fields are disabled before being directed to a new page. My testing methodology involves verif ...

Tips on generating model names dynamically within a service

I am currently utilizing a service to assign unique numbers to model names. The resulting data structure is as follows: "sectionInputs": [ { "model": "price_min1" }, { "model": "price_max2" }, { "model": "units_occ3" }, { "m ...

Separating Angular controllers into their own files can help prevent errors like "undefined is not a

I am currently revamping some Angular code and my goal is to organize things by type, such as keeping controllers in a separate folder. Currently, I have two controllers and an app.js file. However, I am encountering an issue with the error message "undef ...

What is the best way to retrieve a variable within an AngularJS controller?

I am working with a binding parameter eid: '@' Inside my constructor, you will find the following method: this.$onInit = () => { console.log('eid: ', this.eid) } console.log("eid in another section: ", this.eid) Upon running t ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

Tips for adding a sequence of numbers to a database using Angular

How can I add a range of numbers to a database using a form? <form> <input class="form-control"></input> <!-- enter first number --> <input class="form-control"></input> <!-- enter last number --> ...

Utilizing Filters to Dynamically Highlight and Unhighlight HTML in Angular

Currently, I am experimenting with creating a series of filters that can dynamically highlight and remove highlighting from generated HTML: Highlight filter: app.filter('highlight', function ($sce) { return function (str, termsToHighlight) ...

Failed to create Angular controller instance

I need help setting up a basic login feature using AngularJS. Here is my current code: <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>H ...