gpt4 book ai didi

android - Spring RestTemplate : post both an image and an object at the same time

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:43:19 26 4
gpt4 key购买 nike

我的用户可以在我的服务器上张贴食物的照片和食物的内容。

例如,假设有人看到好吃的东西,拍下它的照片,然后写下“好吃!”在图片下方。照片被发送到服务器,消息“好吃!”包括用户名、日期、位置等在内的一个名为“Post”的对象使用一个 API 调用发送到我的服务器。

我在我的android端写了下面的代码:

    final String url = Constants.POST_PICS;
RestTemplate restTemplate = RestClientConfig.getRestTemplate(context, true);
//adding StringHttpMessageConverter, formHttpMessageConverter and MappingJackson2HttpMessageConverter to restTemplate
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
restTemplate.getMessageConverters().add(formHttpMessageConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
//putting both objects into a map
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("image", new FileSystemResource(file));
map.add("post", post);
HttpHeaders imageHeaders = new HttpHeaders();
//setting content type to multipart as the image is a multipart file
imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders);
ResponseEntity<Post> response = restTemplate.exchange(url, HttpMethod.POST, imageEntity, Post.class);
return response.getBody();

这是Spring端的代码:

        @RequestMapping(value = "/uploadpostpic", method = RequestMethod.POST)
public Post uploadPostWithPic(@RequestParam("image") MultipartFile srcFile,
@RequestParam("post") Post post) {
return serviceGateway.uploadPostWithPic(srcFile, post);
}

我收到一个错误:

An exception occurred during request network execution :Could not write request: no suitable HttpMessageConverter found for request type [Model.Post]

org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [Model.Post]

我怀疑这与设置为 MULTIPART_FORM_DATA 的内容类型有关,但我需要将其设置为此,因为我需要将图片传输到服务器。

是否可以同时使用 restTemplate 向上游传输一个多部分文件和另一个对象?

编辑:

我看过这些帖子:

Resttemplate form/multipart: image + JSON in POST

Sending Multipart File as POST parameters with RestTemplate requests

并根据他们的指导尝试了这段代码:

    final String url = Constants.POST_PIC;
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());

FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
formHttpMessageConverter.addPartConverter(new MappingJackson2HttpMessageConverter());
formHttpMessageConverter.addPartConverter(new ResourceHttpMessageConverter()); // This is hope driven programming
formHttpMessageConverter.addPartConverter(new ByteArrayHttpMessageConverter());

restTemplate.getMessageConverters().add(formHttpMessageConverter);

MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();

byte[] bFile = new byte[(int) imageFile.length()];
FileInputStream fileInputStream;

//convert file into array of bytes
fileInputStream = new FileInputStream(imageFile);
fileInputStream.read(bFile);
fileInputStream.close();

ByteArrayResource bytes = new ByteArrayResource(bFile) {
@Override
public String getFilename() {
return "file.jpg";
}
};

//post portion of the multipartRequest
HttpHeaders xHeader = new HttpHeaders();
xHeader.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Post> xPart = new HttpEntity<>(post, xHeader);
multipartRequest.add("post", xPart);

//picture portion of the multipartRequest
HttpHeaders pictureHeader = new HttpHeaders();
pictureHeader.setContentType(MediaType.IMAGE_JPEG);
HttpEntity<ByteArrayResource> picturePart = new HttpEntity<>(bytes, pictureHeader);
multipartRequest.add("srcFile", picturePart);

//adding both the post and picture portion to one httpentity for transmitting to server
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, header);
return restTemplate.postForObject(url, requestEntity, Post.class);

另一方面,post = null,我不确定它为什么为 null。

这就是我想在服务器端做的所有事情:

public Post uploadPostPic(MultipartFile srcFile, Post post) {
Post savedPost = repo.save(post);
}

我正在将它保存到我的存储库中,错误是:

java.lang.IllegalArgumentException: Entity must not be null!

最佳答案

尝试这样的事情:在此处发送 jsonString,稍后使用 objectwriter 将其转换为对象。如果您需要更多解释,请告诉我。

@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public @ResponseBody
String uploadMultipleFileHandler(@RequestParam("name") String[] names,
@RequestParam("file") MultipartFile[] files) {

if (files.length != names.length)
return "Mandatory information missing";

String message = "";
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
String name = names[i];
try {
byte[] bytes = file.getBytes();

// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();

// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();

logger.info("Server File Location="
+ serverFile.getAbsolutePath());

message = message + "You successfully uploaded file=" + name
+ "<br />";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
}
return message;
}
}

已编辑:

最终,我不得不使用 jsonString 来解决我的问题。这并不理想,因为 url 最终会变得很长,但这是解决我的问题的最快方法:

请查看 mykong 关于如何将对象转换为 jsonString 并将它们重新转换回对象的建议:

ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

http://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

关于android - Spring RestTemplate : post both an image and an object at the same time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34109464/

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