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

How to Upload Multiple Files Using FormData() and XMLHttpRequest

Susan Sarandon
Susan SarandonOriginal
2024-10-22 21:04:02691browse

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

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>

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!

Statement:
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