原文链接:https://www.cnblogs.com/codewy/p/13971111.html
使用Spring RestTemplate调其他服务时,批量发送文件出现了序列化失败问题,现把解决方案记录下来,以帮助他人避坑。
报错信息:No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.io.FileDescriptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.LinkedList[0]->org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"])
发送端Controller代码:
@PostMapping(value = "/v1/uploadFiles", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public Object uploadFiles(@RequestPart("files") List<MultipartFile> files) { return fodderApiService.uploadFiles(files); }
发送端Service代码:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
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; }
![复制代码](https://common.cnblogs.com/images/copycode.gif)
接收端Controller代码:
![复制代码](https://common.cnblogs.com/images/copycode.gif)
@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(); }
![复制代码](https://common.cnblogs.com/images/copycode.gif)