Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a file with XmlHttpRequest: Streaming?

I am trying to upload big files with drag and drop. I have this piece of Javascript code:

xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-File-Name', file.name);
xhr.setRequestHeader('X-File-Size', file.size);
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);

where url is a string of the target url and file is a Blob (according to http://www.w3.org/TR/XMLHttpRequest2/#the-send-method) which I have retrieved after a file drag-drop. This code works in Chrome 12, Safari 5 and Firefox 4 and sends the raw contents of the file in the body of the HTTP request.

However, if the file is big enough the request is never sent. Instead, the XMLHttpRequest object fires and error event (without any useful message). This limit is 86Mb in my environment, but it varies from machine to machine.

The javascript console of Chrome shows the message:

POST http://localhost/xfiles/xfiles.php undefined (undefined)

which has nothing to do with my code (which works perfectly with smaller files).

It seems that the browser reads the entire file in memory and before sending it. Probably there is an out of memory exception or something like that that stops the process. In any case, there no HTTP request is sent, so it is certain that the server's limits have nothing to do with this problem.

Anyway, reading the entire file is a waste of resources.

Is there any method to send the file in a streaming fashion, byte by byte, without having to store it in the memory first?

like image 994
linepogl Avatar asked Jun 23 '11 12:06

linepogl


1 Answers

Try using the Blob.slice method to split the Blob up into multiple chunks, and send each one as a separate request.

like image 76
Na7coldwater Avatar answered Sep 22 '22 04:09

Na7coldwater