本文介绍了使用Spring RestTemplate在多部分中发布字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Spring RestTemplate和一个字节数组作为要上载的文件来发布多部分/表单数据,但它总是失败(服务器拒绝,并出现各种错误)。
我正在对ByteArrayResource使用多值映射。我有什么遗漏的吗?
推荐答案是的,缺少某些内容。
我找到了这篇文章:
medium/@voziv/posting-a-byte-array-instead-of-a-file-using-spring-s-resttemplate-56268b45140b
作者提到,为了使用Spring RestTemplate发布字节数组,需要重写ByteArrayResource的getFileName()。
以下是文章中的代码示例:
private static void uploadWordDocument(byte[] fileContents, final String filename) { RestTemplate restTemplate = new RestTemplate(); String fooResourceUrl = "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在多部分中发布字节数组
发布评论