简体   繁体   English

作为 XMLHttpRequest 和 FormData 的一部分发送多个文件

[英]Sending Multiple Files As Part of XMLHttpRequest and FormData

I have a form on my website where people can attach a file.我的网站上有一个表格,人们可以在其中附加文件。 When a button is pressed it keeps the user on the same page (but updates their screen) and the form contents gets sent using formdata in an xmlhttprequest.当按下按钮时,它使用户保持在同一页面上(但更新他们的屏幕),并且使用 xmlhttprequest 中的 formdata 发送表单内容。

This worked fine when it was for one file: <input type="file" id="files" />这适用于一个文件时效果很好: <input type="file" id="files" />

var xml = new XMLHttpRequest(), form = new FormData();
form.append("files", document.getElementById("files").files[0]);

However, I changed my input to allow for multiple files: <input type="file" id="files" multiple="multiple" />但是,我更改了输入以允许多个文件: <input type="file" id="files" multiple="multiple" />

But now I'm not sure how I should adjust the form.append part of the code.但现在我不确定我应该如何调整 form.append 部分代码。

Should I create some kind of loop for the files to append each file separably and and a counter to the end of the append name?我是否应该为 append 每个文件分别创建某种循环,并在 append 名称的末尾创建一个计数器? Like "files1" for the first image and "files2" for the second?像第一个图像的“files1”和第二个图像的“files2”? Is there a more direct way of doing this?有没有更直接的方法来做到这一点?

Of note, the reason I have files[0] for the first part of the code is because that would actually send the image rather than just some text saying that it is an object.值得注意的是,我在代码的第一部分有 files[0] 的原因是因为它实际上会发送图像,而不仅仅是一些文本说它是 object。 Maybe there is a way to send an object and have all the images a part of that object?也许有一种方法可以发送 object 并使所有图像成为 object 的一部分?

Something like this should work for your case scenario:这样的事情应该适用于您的案例场景:

var n_files = document.getElementById('files').files.length;
for (var x = 0; x < n_files; x++) {
    form.append("files[]", document.getElementById("files").files[x]);
}

It's common to forget to change files to files[] .忘记将files更改为files[]是很常见的。
Also important to mention that it depends on how your multipart form will be handled server sided.同样重要的是要提到它取决于您的多部分表单将如何在服务器端处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM