Thunderforge
Thunderforge

Reputation: 20575

File getting corrupted when sending in a PUT request via Spring RestTemplate

I have a file that I am trying to send from one server to another. Since a File object represents a specific location on the file system, and that file won't exist on the new server when I send it, I have to transfer it over some other way.

I figured the best way to send it would be a simple byte array, like so (making use of Apache Commons FileUtils):

File file = <...>;
byte[] fileByteArray = FileUtils.readFileToByteArray(file);
restTemplate.put("http://example.com/upload/", fileByteArray);

I then receive the file on the other end like so:

@RequestMapping(value = "upload/", method = RequestMethod.PUT)
public void upload(
        @NotNull @RequestBody byte[] data
) {
    File file = <...>;
    FileUtils.writeByteArrayToFile(file, data);
}

However, the file on the other end is corrupted. For instance, if I send a zip file over and try to open it up in Windows Explorer, I am told that it is invalid, even though it worked perfectly fine on the other end. What is going on?

Upvotes: 0

Views: 1489

Answers (1)

Thunderforge
Thunderforge

Reputation: 20575

The problem is with sending across the file as a byte[]. Spring is converting it to a String, then turning that String into a byte[] (equivalent to String.getBytes()). This produces a slightly different byte[] than what you started with, which is causing the corruption.

Instead, you should either send across an InputStream or, if you must send across a byte[], send it in a wrapped object.

Upvotes: 3

Related Questions