S
S
Sergey2017-02-20 19:19:41
Spring
Sergey, 2017-02-20 19:19:41

Uploading a file via Spring?

I have a dev server running angular 2 at localhost:4200 and spring tomcat at localhost:8080.
I'm trying to upload a file to the server in the following way:
Angular code:

uploadAvatar(file:File){
        let xhr = new XMLHttpRequest()
        xhr.open("POST",`http://localhost:8080/api/upload/avatar`)
        xhr.setRequestHeader("Content-Type","multipart/form-data")
        xhr.send(file)
    }

Spring controller code:
@RequestMapping(value = "/api/upload/avatar", method = RequestMethod.POST)
    public String uploadFile(MultipartFile file){
        log.info(file);
        return file.getName();
    }

But after trying to download the file in the java console, an error appears:
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; 
nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

How to fix this error?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2017-02-21
@Bleser

Added two bins and everything worked.

@Bean(name = "commonsMultipartResolver")
public MultipartResolver multipartResolver() {
    return new StandardServletMultipartResolver();
}


@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();

    factory.setMaxFileSize("10MB");
    factory.setMaxRequestSize("10MB");

    return factory.createMultipartConfig();
}

R
Ruslan Lopatin, 2017-02-21
@lorus

Enable multipart support

J
Jeffrey, 2017-10-26
@Hardch

Try passing getLazyLoad to a controller function and calling methods not via a constructor:
getLazyLoad.setMethod('message');
getLazyLoad.getMethod();
https://jsfiddle.net/hfuLLp0d/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question