使用Spring RestTemplate在多部分中发布字节数组

编程入门 行业动态 更新时间:2024-10-26 06:26:11
本文介绍了使用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在多部分中发布字节数组

本文发布于:2023-10-11 13:47:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1481870.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字节   Spring   RestTemplate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!