使用Spring RestTemplate在多部分中发布字节数组 [英] POST byte array in multipart using Spring RestTemplate
本文介绍了使用Spring RestTemplate在多部分中发布字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Spring RestTemplate和一个字节数组作为要上载的文件来发布多部分/表单数据,但它总是失败(服务器拒绝,并出现各种错误)。
我正在对ByteArrayResource使用多值映射。我有什么遗漏的吗?
推荐答案
是的,缺少某些内容。
我找到了这篇文章:
作者提到,为了使用Spring RestTemplate发布字节数组,需要重写ByteArrayResource的getFileName()。
以下是文章中的代码示例:
private static void uploadWordDocument(byte[] fileContents, final String filename) {
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; // Dummy URL.
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", filename);
map.add("filename", filename);
// Here we
ByteArrayResource contentsAsResource = new ByteArrayResource(fileContents) {
@Override
public String getFilename() {
return filename; // Filename has to be returned in order to be able to post.
}
};
map.add("file", contentsAsResource);
// Now you can send your file along.
String result = restTemplate.postForObject(fooResourceUrl, map, String.class);
// Proceed as normal with your results.
}
我试过了,很管用!
这篇关于使用Spring RestTemplate在多部分中发布字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文