gpt4 book ai didi

post - RestTemplate 将图像上传为 MultipartFile,内容类型为 image/jpg

转载 作者:行者123 更新时间:2023-12-05 00:52:35 28 4
gpt4 key购买 nike

我正在尝试使用 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);

异常(exception):
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]

上传带有 Content-Type 的作品 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);
RestTemplateResourceHttpMessageConverter它将您的多部分流式传输到您的服务中。

关于post - RestTemplate 将图像上传为 MultipartFile,内容类型为 image/jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141915/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com