'POST byte array in multipart using Spring RestTemplate

I'm trying to POST a multipart/form-data using Spring RestTemplate with a byte array as the file to upload and it keeps failing (Server rejects with different kinds of errors).

I'm using a MultiValueMap with ByteArrayResource. Is there something I'm missing?



Solution 1:[1]

Yes there is something missing.

I have found this article:

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

The author mentions that in order to POST a byte array using Spring RestTemplate one needs to override getFileName() of the ByteArrayResource.

Here is the code example from the article:

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.
}

I tried it and it works!

Solution 2:[2]

I added an issue to send a request from java client to Python service in FastApi and sending a ByteArrayResource instaead of simple byte[] fixed the issue. FastAPI server returned: "Expected UploadFile, received: <class 'str'>","type":"value_error""

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shaiu22
Solution 2 MikaelP