Skip to content Skip to sidebar Skip to footer

Javascript/html5 File Api Reading Sequential Files Into Multipart Form Data

I'm using the HTML5 File API to assemble multipart form data for submission by XHR to a web service. I have the whole thing working in FF, which has a nice convenient getAsBinary(

Solution 1:

What you're going to have to do is have the reader "load" handlers all check to see whether they're the last one to run. When that happens, then that handler can call "sendData()".

varconst;  // constructorconst += headers;
const += field_data;

var reader;
var finished = 0;
for(var i = 0; i < files.length; i++)
{
    reader = newFileReader();
    reader.onload = function(file)
    {
       const += file.target.result;
       if (++finished === files.length)
         sendData(const);
    };
    reader.readAsBinaryString(files[i]);
}

(I don't fully understand the details of how that accumulated "const" thing will correctly turn into a multipart MIME blob, but I presume that you do :-) Also, and this is probably important: I think you probably need to make a new "FileReader" instance for each file. I coded this that way (actually I just edited it) but that may be incorrect, as I'm not that familiar with the API and its semantics.

Solution 2:

Have you considered xhr.send(FormData)? See my response here: upload to php $_FILE from chrome extension

You can append files to a FormData object and send that via xhr. The browser constructs the multi-part request for you. I believe this is available in FF4 and has been in Chrome for some time.

Post a Comment for "Javascript/html5 File Api Reading Sequential Files Into Multipart Form Data"