21

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?

2 Answers 2

43

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!

Sign up to request clarification or add additional context in comments.

3 Comments

you saved my life byte array using Spring RestTemplate one needs to override getFileName() of the ByteArrayResource
Can we do the same with Webflux web client ?
I have a React front, I wanted to develop a Java Web Service in spring boot. I have been struggling for two full days, could not get the proper file sent to the client from web service. this very snippet of overriding getFilename() did the job. I almost put a whatsapp status that stackoverflow is awesome. People are awesome.
0

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""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.