spring - 使用 Spring RestTemplate 在多部分中发布字节数组
问题描述
我正在尝试使用 Spring RestTemplate 发布多部分/表单数据,并将字节数组作为要上传的文件,并且它一直失败(服务器拒绝不同类型的错误)。
我正在使用带有 ByteArrayResource 的 MultiValueMap。有什么我想念的吗?
解决方案
是的,有些东西不见了。
我找到了这篇文章:
作者提到,为了使用 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.
}
我试过了,它有效!
推荐阅读
- python - 标签存在于 HTML 代码中,但无法通过 xpath 访问
- exiftool - 使用 exiftool 将地理标记的图像保存到新目录
- javascript - 使用过滤器过滤对象
- datepicker - Datepicker Materializecss 禁用天数功能
- javascript - ASP.NET JQuery - jQuery.Deferred 异常:$ 不是函数
- javascript - Javascript 打印 node.js 版本和模块版本
- sql - 如何在 SQL Server 中将 html 文本转换为表格格式的纯文本
- json - 我们如何格式化或转换 Xcode 日志或以 JSON 格式打印?
- ssh - 为什么“ssh root@server”需要 id_dsa 密钥?
- r - 使用 ggplot 在雷达图中错误绘制 NA 数据