我正在尝试使用 feign 客户端将文件上传到 REST api。如下所示并且工作正常。
@PostMapping(value = "/test/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<String> upload(@RequestPart(value = "data") MultipartFile zipFile);
为了为更新创建 Multipart 文件,我这样做了,
public MultipartFile createFile(){
String zipFilePath = "some/path/to/file";
File file = new File(zipFilePath);
FileItem fileItem = new DiskFileItem(FIELD_NAME, Files.probeContentType(file.toPath()), false,
file.getName(), (int) file.length(), file.getParentFile());
try (InputStream input = new FileInputStream(file); OutputStream output = fileItem.getOutputStream()){
IOUtils.copy(input, output);
}
return new CommonsMultipartFile(fileItem);
}
调用 feign 客户端时,正在使用从上述方法创建的 Multipart File。我没有像上面那样创建并将CommonsMultipartFile
其加载到内存中,而是决定将其加载到Resource
如下所示,
public Resource createFile(){
String zipFilePath = "some/path/to/file";
Resource resource = new FileSystemResource(zipFilePath );
return resource;
}
并像这样更改了伪装客户端方法,但是在伪装客户端中它不起作用。
@PostMapping(value = "/test/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<String> upload(@RequestPart(value = "data") Resource zipFile);
我收到来自端点Status: 409 CONFLICT. Body: Nothing to upload
响应的错误。/test/upload
但后来我尝试使用一个休息模板上传资源,该模板对资源作为文件数据工作得很好,
public ResponseEntity<String> uploadFile(Resource file){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
HttpEntity<Resource> fileResource = new HttpEntity<>(file);
parts.add("data", fileResource);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
}
什么原因是它不起作用在 feign 客户端中将资源类型作为部分数据传递。我正在使用spring spring boot 2.x。