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() method included in their implementation of the file API. This was a pretty sweet deal. It basically went:
var const; // constructor
const += headers;
const += field_data;
for(var i = 0; i < files.length; i++)
{
const += files[i].getAsBinary();
}
sendData(const);
Worked like a charm.
To get it working in Chrome, though, I have to make a FileReader object, which handles a bit differently. I essentially have to go:
var const; // constructor
const += headers;
const += field_data;
var reader = new FileReader();
for(var i = 0; i < files.length; i++)
{
reader.onload = (function(file)
{
const += file.target.result; // const is not in scope in this anonymous function!
}
reader.readAsBinaryString(files[i]);
}
sendData(const);
Which doesn't work, for two main reasons. Firstly, the read happens asynchronously, so by the time it gets to the sendData() function, the file data isn't written to the const variable. Secondly, the const variable is out of scope inside the reader.onload handler. However I re-jig the code, I seem to come across one of these obstacles, and I'm struggling to come up with a graceful way of handling it.
Any suggestions?