简体   繁体   中英

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.

This worked fine when it was for one file: <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" />

But now I'm not sure how I should adjust the form.append part of the code.

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? Like "files1" for the first image and "files2" for the second? 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. Maybe there is a way to send an object and have all the images a part of that 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[] .
Also important to mention that it depends on how your multipart form will be handled server sided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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