Home > Web Front-end > JS Tutorial > How to Upload Multiple Files Using FormData() and XMLHttpRequest

How to Upload Multiple Files Using FormData() and XMLHttpRequest

Susan Sarandon
Release: 2024-10-22 21:04:02
Original
756 people have browsed it

How to Upload Multiple Files Using FormData() and XMLHttpRequest

Uploading Multiple Files with formData()

The code snippet provided allows you to upload a single file using the FormData() interface and XMLHttpRequest. To enable the upload of multiple files, however, the approach needs to be modified.

JavaScript:

Remove the [0] index from the append statement and use a loop to iterate through the selected files. The files.length property determines the number of files chosen.

<code class="javascript">var files = document.getElementById('fileToUpload').files;
for (var x = 0; x < files.length; x++) {
    fd.append("fileToUpload[]", files[x]);
}
Copy after login

PHP:

On the server-side, retrieve the uploaded files using the following code:

<code class="php">$count = count($_FILES['fileToUpload']['name']);
for ($i = 0; $i < $count; $i++) {
    echo 'Name: ' . $_FILES['fileToUpload']['name'][$i] . '<br/>';
}</code>
Copy after login

You can use this method to upload multiple files with individual names and process them on the server as needed.

The above is the detailed content of How to Upload Multiple Files Using FormData() and XMLHttpRequest. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template