Posting File Input as FileReader Binary Data through AJAX Post
Simply sending the file
reference as data (with processData: false
) did the job for me at least:
$('#_testButton').bind('click', function () { var file = document.getElementById('_testFile').files[0]; $.ajax({ url: "/attachmentURL", type: "POST", data: file, processData: false });});
It is described here: https://developer.mozilla.org/en/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data#section_3
Sending a string (even if that string represents binary data) will not work because the browser will forcibly turn it into unicode and encode as utf-8 as specified which will corrupt the binary data:
If data is a string Let encoding be UTF-8.
Let mime type be "text/plain;charset=UTF-8".
Let the request entity body be data converted to Unicode and encoded as UTF-8.
Sending a file
reference (blob
) will do this:
If data is a Blob If the object's type attribute is not the empty string let mime type be its value.
Let the request entity body be the raw data represented by data.
var file;
$('#_testFile').on("change", function (e) { file = e.target.files[0]; }); $('#_testButton').click(function () { var serverUrl = '/attachmentURL'; $.ajax({ type: "POST", beforeSend: function (request) { request.setRequestHeader("Content-Type", file.type); }, url: serverUrl, data: file, processData: false, contentType: false, success: function (data) { console.log("File available at: ", data); }, error: function (data) { var obj = jQuery.parseJSON(data); alert(obj.error); } }); });