http - 使用 XMLHttpRequest Level 2 模拟文件表单提交

标签 http http-headers xmlhttprequest

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

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

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

最佳答案

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

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

关于http - 使用 XMLHttpRequest Level 2 模拟文件表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9963514/

相关文章:

python - 读取在 ajax 中传递的自定义 header

ios - 如何在 Swift 中发送这样的 HTTP POST?

javascript - 如何选择在 D3 力定向图中使用哪个 JSON 文件

javascript - vue.js 中的 $http.get() 与 axios.get() 有什么区别?

http - CORS 与 POSTMAN

php - 将 PHP 页面作为图像返回

firefox - 是否有一个 Firefox 插件可以列出导致 "Warning: Contains unauthenticated content"的不安全 Assets

http - 最佳实践 : HTTP code for user exceeding usage limitation

xmlhttprequest - CORS 请求已预检,但似乎不应该

json - 打开网页,全选,复制到工作表