简体   繁体   中英

Spring Boot + multipart/form-data controller method

Can't seem to figure this out, no matter what I try. I'm submitting this curl command:

curl -v -F name=countries.zip -F filedata=@countries.zip http://localhost:8080/rest

I have a Spring Boot 1.4 app with an annotated @RestController with the following method:

@RequestMapping(consumes = {"multipart/form-data"}, method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, path = {"/rest", "/rest/**"})
public void handleMultipartRestApiRequest(MultipartHttpServletRequest request, HttpServletResponse response, @RequestPart(value = "filedata", required = false) MultipartFile filedata) throws Exception {
    r...
}

The filedata variable is always null, and the request object always shows 0 files.

I've tried multiple configurations with a MultipartResolver. Here is my latest:

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(5000000);
    multipartResolver.setMaxInMemorySize(5000000);
    multipartResolver.setDefaultEncoding("utf-8");
    return multipartResolver;
}

I also manually stuck these in my application.properties just to be 1000% sure it's not disabled:

multipart.enabled=true

spring.http.multipart.enabled=true

and for good measure, here are the request headers:

   * Connected to localhost (::1) port 8080 (#0)
> POST /rest HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Length: 817999
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------7d3f4606455e862b
> 

Anybody have a clue why I can't seem to be able to see the file on my controller?

UPDATE 1:

If I dig far enough into the request object and get to the org.catalina.connector.Request object, there is an ArrayList of ApplicationPart items that contain a DiskFileItem that seems to hold information about the file I'm trying to upload. This is actually the Collection that is returned when you call request.getParts(). The file item location path is some long tmp path:

/private/var/folders/n8/15d6vbhj0692cslf3cx8c1jm0000gn/T/tomcat.6840182548028446450.8080/work/Tomcat/localhost/myapp

However it also says the content type is application/octet-stream, the size is -1, and some other weirdness, like "isFormField" is false even though i'm specifying it as a form field in my curl command. So spring is calling the correct method to handle a multipart/form-data request, but yet the "part" information seems to think it's an octet-stream.

i'll share my function to upload a file using MultipartFile there's no need of a resolver or a bean, but you only can send the file alone, not with another type of param or body.

@RequestMapping(value = "/updatePhoto", method = RequestMethod.POST)
public @ResponseBody
    ResponseEntity<?> updateUsuario(@RequestParam("file") MultipartFile file,
        OAuth2Authentication authentication) {
    try {
        User user = (User) authentication.getPrincipal();
        Usuarios u = usuariosDAO.findUsuarioByUsername(user.getUsername());
        if (file.getName().isEmpty() == false) {
            InputStream inputStream = file.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] bytes = new byte[16384];
            while ((nRead = inputStream.read(bytes, 0, bytes.length)) != -1) {
                buffer.write(bytes, 0, nRead);
            }
            buffer.flush();
            u.setImagen(buffer.toByteArray());
            usuariosDAO.updateUsuario(u);
        }
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}

In this case i upload a photo for a profile user, and convert it to an array of bytes. Then its saved on a database. hope this help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM