Javascript/HTML5 file API reading sequential files into multipart form data

后端 未结 2 1155
栀梦
栀梦 2021-01-03 06:50

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 getA

相关标签:
2条回答
  • 2021-01-03 07:09

    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.

    0 讨论(0)
  • 2021-01-03 07:17

    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()".

    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 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.

    0 讨论(0)
提交回复
热议问题