Bằng Rikimaru
Bằng Rikimaru

Reputation: 1595

Spring Boot - get uploaded files in a controller without knowing key parameters with POST request?

I use Spring Boot 1.5.2 and I have a controller to handle a POST request which can contain a random uploaded files as binary and random keys values as string with different POST parameters.

For example:

curl -F 'fileX=@/path/to/fileX' 
     -F 'fileY=@/path/to/fileY'
     -F 'abc=@/path/to/fileZ' 
     -d "key1=value1"
     -d "key2=value2"

http://localhost/upload

I've searched for MultipartFile[], but it seems it needs to have a fixed key parameter, otherwise this files variable will be null, e.g:

@Controller
public class FilesController {

    @PostMapping("/upload")
    public void handlePost(HttpServletRequest httpServletRequest, 
                           HttpServletResponse httpServletResponse, 
                           @RequestParam("filesKey") MultipartFile[] files) {
 
    }
}

How can I get the list of posted files in this case without knowing the key parameters of them?

Upvotes: 0

Views: 640

Answers (1)

Bằng Rikimaru
Bằng Rikimaru

Reputation: 1595

I think the uploaded files can be achieved like this below:

@PostMapping("/upload")
public void handlePost(HttpServletRequest httpServletRequest, 
                       HttpServletResponse httpServletResponse) {

        for (Part part : httpServletRequest.getParts()) {
            System.out.println(part.getContentType());
            System.out.println(part.getName());
        }

}

which will output:

application/octet-stream
fileX
application/octet-stream
fileY
application/octet-stream
abc
null
key1

Upvotes: 1

Related Questions