其他分享
首页 > 其他分享> > 使用Spring RestTemplate 发送 List<MultipartFile>,上传多个文件

使用Spring RestTemplate 发送 List<MultipartFile>,上传多个文件

作者:互联网

 

发送端Controller代码:

    @PostMapping(value = "/v1/uploadFiles", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Object uploadFiles(@RequestPart("files") List<MultipartFile> files) {
        return fodderApiService.uploadFiles(files);
    }

 

发送端Service代码:

public Object uploadFiles(List<MultipartFile> files) {

        String remoteUrl = "http://aaa.com/v1/uploadFiles";
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<>();

        Object respBody = null;
        try {

            for(MultipartFile file : files) {
                ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
                    @Override
                    public String getFilename() {
                        return file.getOriginalFilename();
                    }
                };
                paramsMap.add("files", resource);
            }

            // 构造请求的实体。包含body和headers的内容
            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(paramsMap, headers);
            respBody = restTemplate.postForEntity(remoteUrl, request, Object.class).getBody();
        } catch (Exception e) {
            logger.error("上传文件失败:", e);
        }

        return respBody;
    }

 

接收端Controller代码:

    @RequestMapping(value = "/v1/uploadFIles", method = RequestMethod.POST,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Object uploadFiles(@RequestPart("files") List<MultipartFile> files) {
        
     // do something...

        return new Object();
    }

 

标签:files,return,Spring,Object,RestTemplate,new,List,public,uploadFiles
来源: https://www.cnblogs.com/codewy/p/13971111.html