作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 RestTemplate 将图像(MultipartFile)上传到服务器 URL。
来自 postman 的发送请求与 Content-Type: image/jpg
一起使用和从正文作为二进制文件发送的图像。
SpringBoot中的方法实现:
public ResponseEntity<String> uploadImage(MultipartFile file) {
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
restTemplate.getMessageConverters().add(new BufferedImageHttpMessageConverter());
LinkedMultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
params.add("file", new FileSystemResource(file));
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, httpHeaders);
return restTemplate.exchange(UPLOAD_URL, HttpMethod.POST, requestEntity, String.class);
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [image/jpeg]
MediaType.MULTIPART_FORM_DATA
但我使用的 REST 服务只接受
image/jpg
作为 HTTP 内容类型。
最佳答案
您的远程服务接受 image/jpg
所以你应该流式传输字节而不是多部分:
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpeg");
Resource res = new InputStreamResource(file.getInputStream());
HttpEntity<Resource> entity = new HttpEntity<>(res, headers);
template.exchange(UPLOAD_URL, HttpMethod.POST, entity , String.class);
RestTemplate
有
ResourceHttpMessageConverter
它将您的多部分流式传输到您的服务中。
关于post - RestTemplate 将图像上传为 MultipartFile,内容类型为 image/jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141915/
我有以下正则表达式 /[a-zA-Z0-9_-]/ 当字符串只包含从 a 到z 大小写、数字、_ 和 -。 我的代码有什么问题? 能否请您向我提供一个简短的解释和有关如何修复它的代码示例? //var
我是一名优秀的程序员,十分优秀!