我正在尝试使用多部分表单数据执行 POST 请求。我有这个控制器接收请求
@PostMapping(value = "/photos", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "Accepts photo. Adds photo to queue for sending to Telegram chat")
private void sendPhotos(@RequestPart List<MultipartFile> photos,
@RequestParam long cityId,
@RequestParam(required = false) String caption) {
sendToCityChatUseCase.execute(photos, cityId, caption);
}
我正在使用 RestTemplate 发送 MultipartFile 列表:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> files = new LinkedMultiValueMap<>();
for (MultipartFile file : photos) {
files.add("photos", file);
}
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(files, headers);
ResponseEntity<String> response = restTemplate.postForEntity(chatBotUrl, requestEntity,String.class);
当我使用这样的实现时,我得到一个异常:
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: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"])
当我将
files.add("photos", file);
更改为 files.add("photos", file.getBytes());
时,我已设法执行请求,但得到 MissingServletRequestPartException
,因为该请求中没有 photos
部分。
我想我错过了一些东西。我自己编写新的转换器并不愉快,希望还有其他方法
我认为您的类型不匹配,您应该将您的客户端更改为:
MultiValueMap<String, List<MultipartFile>> files = new LinkedMultiValueMap<>();
files.add("photos", photos); //No loop here since server expects list
您可能想在属性文件中添加
spring.jackson.serialization.fail-on-empty-beans=false