How do I send binary data as raw POST?

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?

  • 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

    – 

  • @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).

    – 

  • @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.

    – 

Leave a Comment