问题
On my current page I use old file upload with input element. However, now I've implemented drag&drop from that very nice series of articles: http://www.sitepoint.com/html5-file-drag-and-drop/
There's one snag. Before rewriting the page I was submitting the form with the file and server side service (Java's appspot.com) did all the magic of retrieving the file, saving to DB etc. I would still like to take advantage of that service. However now, after rewriting the file upload to use XMLHttpRequest my code simply writes file to the content, whereas service expects form.
Is there a way to mimick miltipart/form-data form submission with XMLHttpRequest?
回答1:
The FormData object can be used to submit multipart/form-data forms.
Basic example:
var fd = new FormData(); // Optionally: new FormData(htmlFormElement);
fd.append('key', 'value');
fd.append('file', reference_to_File_object);
// ^ Example: .files property of an <input type="file"
var xhr = new XMLHttpRequest();
xhr.open('post', '/postdata', true);
xhr.send(fd);
When strings are passed to the .send() method of an XMLHttpRequest instance, it is converted to unicode, then encoded as UTF-8. This means that a custom multipart/form-data implementation, using strings, will often not work correctly.
来源:https://stackoverflow.com/questions/9963514/simulate-file-form-submission-with-xmlhttprequest-level-2