Javascript / HTML5 API that reads sequential files into multiphase form data

I am using the HTML5 file API to build multi-page form data to submit XHR to a web service. I have everything that works in FF, which has a convenient convenient getAsBinary () method included in their implementation of the API files. It was a pretty nice deal. He 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 make it work in Chrome, I have to create a FileReader object that processes the 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 does not work for two main reasons. Firstly, reading occurs asynchronously, therefore, by the time the sendData () function is received, the file data is not written to the constant variable. Secondly, the const variable goes beyond the scope inside the reader.onload handler. However, I am rewriting the code, I seem to encounter one of these obstacles, and I am struggling to come up with an elegant way to handle it.

Any suggestions?

+4
source share
2 answers

What you need to do is check that the "load loaders" handlers check to see if they will be the last to run. When this happens, this handler may call sendData ().

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

(I don’t quite understand the details of how this accumulated "const" thing will correctly turn into a multi-part MIME block, but I suppose you do this :-) Also, and this is probably important: I think you, it is probably necessary to create a new instance of "FileReader" for each file. I encoded it this way (in fact, I just edited it), but this may not be true, as I am not familiar with the API and its semantics.

+3
source

Did you consider xhr.send(FormData) ? See my answer here: upload to php $ _FILE from chrome extension

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

0
source

Source: https://habr.com/ru/post/1344380/


All Articles