Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload via JavaScript: Invalid file on server

I'm trying to upload a binary file (a PDF to be specific) with this JS-Snippet:

function uploadFile() {
    var reader = new FileReader();
    var file = document.getElementById('uploadInput').files[0];
    console.log(file.size);
    var xhr = new XMLHttpRequest();

    xhr.open('POST', 'custom?id=upload');
    xhr.setRequestHeader("Content-Type", "application/pdf");
    xhr.overrideMimeType('application/pdf');
    reader.onload = function(evt) {
        xhr.send(evt.target.result);
    };
    reader.readAsBinaryString(file);
}

On the serverside (Java) I'm receiving the request and writing the file to disk.
But instead of the expected ~3MB I'm getting ~4MB, with the effect that I only have blank pages, when opening the PDF.

The header of the incoming request also specifies a Content-Length of ~4MB, so I'm fairly certain, that it is something on the clientside, that is causing the trouble.
Sending plain text files is no problem at all, they arrive exactly as they are supposed to be.

Since writing JavaScript and working in the web is not in my daily field of work, it is very well possible that I did something fundamentelly wrong.

like image 723
TiGro Avatar asked Mar 17 '26 01:03

TiGro


1 Answers

I would suspect 2 things you can try out:

  • check the MIME type on both end of the process, if it gets mangled somehow you have your answer
  • Your upload gets wrapped into a XMLHttprequest - you might have to Base64 Encode/Decode manually to get rid of the native byte representation in the PDF

Hopefully this will help you, good luck!

like image 152
Christian Meißler Avatar answered Mar 19 '26 15:03

Christian Meißler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!