Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload a binary file using pure JavaScript

I'm working on a Chrome app that uses the HTML5 Filesystem API, and allows users to import and sync files. One issue I'm having is that if the user tries to sync image files, the files get corrupted during the upload process to the server. I'm assuming it's because they're binary.

For uploading, I opted just to make an Ajax POST request (using MooTools) and then put the file contents as the body of the request. I told MooTools to turn off urlEncoding and set the charset to "x-user-defined" (not sure if that's necessary, I just saw it on some websites).

Given that Chrome doesn't have support for xhr.sendAsBinary, does anyone have any sample code that would allow me to send binary files via Ajax?

like image 398
Jordon Wii Avatar asked May 12 '11 14:05

Jordon Wii


1 Answers

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.

like image 105
ebidel Avatar answered Oct 02 '22 20:10

ebidel