Dupuis David
Dupuis David

Reputation: 421

Spring MVC - Ajax file upload doesn't work

I'm trying to upload a file dynamically using AJAX and Spring MVC.

Here is what I'm doing:

Javascript function:

function initQwacCertificate(){
  $('#qwac').on('change', function(){
      var formData = new FormData();
      var file = $('#qwac')[0].files[0];

      formData.append("myFileKey", file);

      $.ajax({
          url : postQwac,
          type : 'POST',
          data : formData,
          enctype : 'multipart/form-data',
          contentType : false,
          cache : false,
          processData : false,
          success : function(response) {},
      });
  });
};

Java controller:

@PostMapping(value = "/extractQwacCertificate", consumes = { "multipart/form-data" })
        ExtractedQwacCertificate extractQwacCertificate(@RequestParam("myFileKey") MultipartFile uploadedFile) throws IOException, CertificateException {
            //MyStuff
}

All that stuff return my an 400 error in my JS console that I can't understand:

Required request part 'myFileKey' is not present

But for me this 'myFileKey' is present! There is something I do in the wrong way but I don't know what! Does anyone see what's wrong ?

Thank you

Upvotes: 0

Views: 89

Answers (1)

Paul Warren
Paul Warren

Reputation: 2479

You probably don't have the StandardServletMultipartResolver registered (or CommonsMultipartFile prior to servlet 3.0). Without a MultipartResolver Spring does not know how to extract the file from the request.

For servlet 3.0 you would need to add this to your dispatcher servlet:

public class MainWebAppInitializer implements WebApplicationInitializer {

    private String TMP_FOLDER = "/tmp"; 
    private int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; 

    @Override
    public void onStartup(ServletContext sc) throws ServletException {

        ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(
          new GenericWebApplicationContext()));

        appServlet.setLoadOnStartup(1);

        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(TMP_FOLDER, 
          MAX_UPLOAD_SIZE, MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);

        appServlet.setMultipartConfig(multipartConfigElement);
    }
}

And then register the multipart resolver (java config example given):

@Bean
public StandardServletMultipartResolver multipartResolver() {
    return new StandardServletMultipartResolver();
}

Upvotes: 1

Related Questions