Uploading a List of MultipartFile with Spring 4 restTemplate (Java Client & RestController)

后端 未结 1 1713
抹茶落季
抹茶落季 2020-12-18 14:16

I am trying to post of List of MultipartFile to my RestController using spring restTemplate although I\'m a bit confused as to the exact syntax & types to use for my cli

相关标签:
1条回答
  • 2020-12-18 14:46

    It looks like the request payload that you are sending from FileUploadClient does not match what's server is expecting. Could you try changing the following:

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    for(MultipartFile file : multiPartFileList) {
        map.add(file.getName(), new ByteArrayResource(file.getBytes()));
    }
    

    to

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    List<ByteArrayResource> files = new ArrayList<>();
    for(MultipartFile file : multiPartFileList) {
        files.add(new ByteArrayResource(file.getBytes()));
    }
    map.put("files", files);
    

    Also, could you try changing the server's method signature to the following:

    public ResponseEntity<?> uploadFiles(@RequestParam("files") List<MultipartFile> files, HttpServletRequest request) {
    

    Update

    While uploading multiple files, you need to make sure getFileName of ByteArrayResource returns same value every time. If not, you will always get an empty array.

    E.g. the following works for me:

    Client:

    MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>(); 
    for(MultipartFile file : multiPartFileList) { 
        ByteArrayResource resource = new ByteArrayResource(file.getBytes()) { 
            @Override 
            public String getFilename() { 
                return ""; 
            } 
        }; 
        data.add("files", resource);
    } 
    

    Server

    public ResponseEntity<?> upload(@RequestParam("files") MultipartFile[] files){
    
    0 讨论(0)
提交回复
热议问题