Upload a binary file using pure JavaScript Upload a binary file using pure JavaScript google-chrome google-chrome

Upload a binary file using pure JavaScript


FF's xhr.sendAsBinary() is not standard. XHR2 supports sending files (xhr.send(file)) and blobs (xhr.send(blob)):

function upload(blobOrFile) {  var xhr = new XMLHttpRequest();  xhr.open('POST', '/server', true);  xhr.onload = function(e) { ... };  // Listen to the upload progress.  xhr.upload.onprogress = function(e) { ... };  xhr.send(blobOrFile);}

You can also send an ArrayBuffer.


IF you're writing the server, then you can just transform the bytes that you read into pure text, send it to the server and then decode it back.

Here's the simplest way (not very efficient, but that's just to show the technique) -

translate each byte you read from the file into a string of two hexadecimal characters. If you read the byte 53 (in decimal) then translate it into "45" (the hexadecimal representation of 53). concatenate all these strings together, and send the resulting string to the server.

On the server side, break the string on even positions, translate each pair of digits into a byte.