我遇到了这个纯 js ajax 上传代码(似乎 jquery $.post
出于某种原因不适用于 HTML5),
/* If you want to upload only a file along with arbitary data that
is not in the form, use this */
var fd = new FormData();
fd.append("file", document.getElementById('file').files[0]);
/* If you want to simply post the entire form, use this */
//var fd = document.getElementById('form1').getFormData();
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "Upload.php");
xhr.send(fd);
但是我这里有两个问题,
- 对象
FormData
之后的这一行是什么意思?
fd.append("file", document.getElementById('file').files[0]);
为什么我在那里需要身份证?我可以使用 jquery append()
和 $('input[type=file]')
做些什么吗?
- 此 ajax 仅适用于单个文件上传,如何更改为多个文件上传?
最佳答案
what does this line mean after the object FormData?
fd.append("file", document.getElementById('file').files[0]);
document.getElementById('file')
得到 <input type="file" id="file">
元素的 ID。 element.files[0]
从元素中获取第一个选定的文件。 fd.append("file", file)
将其附加到 FormData
字段名称为 file
的实例. fd
稍后将作为 multipart/form-data
发送XHR 请求正文。
Why do I need an ID there? Can I do something use jquery
append()
with$('input[type=file]')
?
ID 不是必需的。这毕竟只是一个示例,以便能够获得 <input type="file">
通过其 ID 从文档中获取。请注意 append()
此示例中的函数是 the FormData
API 的一部分不要与 jQuery 的 append()
混淆功能。另请注意 append()
的第一个参数表示字段名称,而不是 ID。它们相同只是巧合。
This ajax is only for single file upload, how can I change it for multiple files upload?
只需将多个字段附加到 FormData
.假设你有一个 File[]
, 这是一个例子:
for (var i = 0; i < files.length; i++) {
fd.append("file" + i, files[i]);
}
它将在服务器端通过字段名称可用 file0
, file1
等
关于jquery - HTML5 AJAX 多文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7138989/