使用XMLHttpRequest Level 2模拟文件表单提交 [英] Simulate file form submission with XMLHttpRequest Level 2

查看:152
本文介绍了使用XMLHttpRequest Level 2模拟文件表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的页面上,我使用带有input元素的旧文件上传。但是,现在我已经从一系列非常好的文章中实现了拖放: http://www.sitepoint.com/html5-file-drag-and-drop/

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/

有一个问题。在重写页面之前,我提交了带有文件和服务器端服务的表单(Java的appspot.com),它完成了检索文件,保存到数据库等的所有魔力。我仍然希望利用该服务。但是现在,在重写文件上传以使用XMLHttpRequest后,我的代码只是将文件写入内容,而服务需要表单。

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.

有没有办法模仿miltipart / form-使用XMLHttpRequest提交数据表单?

Is there a way to mimick miltipart/form-data form submission with XMLHttpRequest?

推荐答案

FormData 对象可用于提交 multipart / form-data 表格。

基本示例:

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);

当字符串传递给 XMLHttpRequest的TR / XMLHttpRequest / #the-send-methodrel =nofollow> .send() 方法实例,转换为unicode,然后编码为UTF-8。这意味着使用字符串的自定义 multipart / form-data 实现通常无法正常工作。

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.

这篇关于使用XMLHttpRequest Level 2模拟文件表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆