使用 Spring RestTemplate 多部分 POST 字节数组

sha*_*u22 7 spring multipartform-data

我正在尝试使用 Spring RestTemplate 和一个字节数组作为要上传的文件发布多部分/表单数据,但它一直失败(服务器因不同类型的错误而拒绝)。

我正在使用带有 ByteArrayResource 的 MultiValueMap。有什么我想念的吗?

sha*_*u22 15

是的,缺少一些东西。

我找到了这篇文章:

https://medium.com/@voziv/posting-a-byte-array-instead-of-a-file-using-spring-s-resttemplate-56268b45140b

作者提到,为了使用 Spring RestTemplate POST 一个字节数组,需要覆盖 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.
}
Run Code Online (Sandbox Code Playgroud)

我试过了,它有效!

  • 我可以吻你(我赞成你的回答)。谢谢 (2认同)