RestTemplate将文件作为字节从一个控制器发送到另一个控制器

时间:2017-04-24 20:01:13

标签: java spring spring-boot resttemplate

假设我们在第三方服务上有一个控制器,它接受多部分文件,其代码就像(假设它在localhost:9090上运行)

@RequestMapping("/file")
@RestController
public class FileController {

    @RequestMapping(value = "/load", method = RequestMethod.POST)
    public String getFile(@RequestPart("file") MultipartFile file){
        return file.getName();
    }

}

问题是: 如何使用RestTemplate在我的控制器中编写一个正确的代码,该代码调用第三方服务,并且文件在正文中?

一些不起作用的例子:

第一个:

@RequestMapping("/file")
@RestController
public class FileSendController {

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ResponseEntity<?> sendFile(@RequestPart MultipartFile file) 
    throws IOException {
    String url = "http://localhost:9090/file/load";
    return restTemplate.postForEntity(url, file.getBytes(), 
    ResponseEntity.class);
    }
}

第二个:

@RequestMapping("/file")
@RestController
public class FileSendController {

    private RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ResponseEntity<?> sendFile(@RequestPart MultipartFile file) 
    throws IOException {
        String url = "http://localhost:9090/file/load";
        byte[] bytes = file.getBytes();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<byte[]> entity = new HttpEntity<>(bytes, headers);
        return restTemplate.exchange(url, HttpMethod.POST, 
        entity,ResponseEntity.class);
    }
}

一个限制:我应该从内存加载文件,因此它强制我使用byte []

所有这些示例都在第三方服务上抛出了500条消息: org.springframework.web.multipart.MultipartException:当前请求不是 多部分请求。

感谢您的建议。

1 个答案:

答案 0 :(得分:3)

试试这个:

MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>();
ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
        @Override
        public String getFilename() {
            return file.getName();
        }
};
data.add("file", resource);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(data, requestHeaders);

final ResponseEntity<Response<ImportDto>> responseEntity = restTemplate.exchange(url, 
                    HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Response<ResponseDto>>(){});