首页 > 解决方案 > 使用 Spring RestTemplate 在多部分中发布字节数组

问题描述

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

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

标签: springmultipartform-data

解决方案


是的,有些东西不见了。

我找到了这篇文章:

https://medium.com/@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 = "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.
}

我试过了,它有效!


推荐阅读