The received file is larger then the sent file

This is the code that sends the file:

byte[] data = FileUtils.readFileToByteArray(new File("my_file.docx"));

System.out.println(data.length); // prints 6408

ResponseEntity<byte[]> responseEntity = makeResponse(data, HttpStatus.OK, DOCX);

return responseEntity;


private <T> ResponseEntity<T> makeResponse(T responseParameter, HttpStatus httpStatus,
                                           DocumentFormat documentFormat) {
    HttpHeaders headers = new HttpHeaders();

    String filename;

    switch (documentFormat) {
        case PDF:
            headers.setContentType(MediaType.parseMediaType("application/pdf"));
            filename = "output.pdf";
            break;
        case DOCX:
            headers.setContentType(MediaType.parseMediaType("application/docx"));
            filename = "output.docx";
            break;
        default:
            throw new IllegalArgumentException(documentFormat.name() + "is not supported");
    }

    headers.setContentDispositionFormData(filename, filename);
    return new ResponseEntity<>(responseParameter, headers, httpStatus);
}

The received file is of size 8546 bytes. The sent file is of size 6408 bytes. Even if the encoding is somehow wrong, the received file should be of the same size, right? The internals of the received file look like two pages of some random characters, "UEsDBBQACAgIANqVt0YAAAAAAAAAAAAA" <- something like this.

I tried to write the byte array that i have read from my_file.docx to a file on my local disk before sending the response and it works ok.

I also tried to setContentLength of the header i'm sending, but it yields the same result - wrong contents of the received file, even though the size is correct.

Any idea where the additional 2Kb are from? And how do i fix this error?

Jon Skeet
people
quotationmark

It's not clear exactly what's actually sending the file, but it's being transmitted as base64 - which is why it's 4/3 the size of the original.

I'm pretty sure if you run the received file through a base64 decoder you'll get the original data. Have a look in the headers and I suspect you'll find base64 mentioned in there.

That should probably give you a hint about how to send the file without using base64 - presumably something defaults to base64 within the framework you're using, and you can probably override it to send the data as just binary.

people

See more on this question at Stackoverflow