0

I am using this code to POST binary data to a REST interface:

var file = $("#file-to-upload")[0].files[0];
var filename = file.name;
var url = "/upload";
const reader = new FileReader();
reader.onload = function(e) {
    console.log(`Read file data: length: ${e.target.result.length}`);
    $.post({
        url: url, 
        data: e.target.result, 
        headers: {
            "Content-Type": "application/octet-stream",
            "Content-Disposition": `attachment; filename=${filename}`
        },
        success: function(r) {
            console.log(r);
        }
    }).fail(function(xhr, status, error) {
        console.log(xhr);
    });
}
reader.readAsBinaryString(file);

The console correctly says the number of bytes in the file. But when checking the actual POST in the development tools, I can see it sends more data:

enter image description here

enter image description here

e.target.result is a binary string, not serialized (strangely enough the dev console says 26.8kB, while the string length is 12817).

enter image description here

What am I missing here?

4
  • I would think that you would create new Form Data not just read the data from a file when Posting it. Post Data should be an Object for jQuery Post. Is the data serialized? Can you provide an example of e.target.result Commented Nov 8, 2023 at 22:32
  • @Twisty e.target.result is a binary string which is exactly the file I uploaded (see updated question). Data is not serialized (that is kind of the point). Commented Nov 9, 2023 at 8:47
  • @Twisty I know I can fix this by Base64 encoding the binary data, but I would like to prevent that (as this means more code on both sides). If there is no other way in JavaScript, then I guess I have no choice. Commented Nov 9, 2023 at 8:51
  • I was suggesting that the resulting data be a part of an Object, like data: { binary: e.target.result },. Commented Nov 9, 2023 at 15:48

0

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.