Simulate file form submission with XMLHttpRequest Level 2

做~自己de王妃 提交于 2019-12-07 22:23:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!