0

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

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.