Home  >  Article  >  Web Front-end  >  How to Upload Multiple Files Using FormData() in JavaScript and PHP?

How to Upload Multiple Files Using FormData() in JavaScript and PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 22:48:02323browse

How to Upload Multiple Files Using FormData() in JavaScript and PHP?

Uploading Multiple Files with formData()

The provided code is functional for uploading a single file using formData(), but to enable uploading multiple files, slight modifications are required.

Solution:

To upload multiple files, the files[] property and a loop through the chosen files are necessary:

JavaScript:

var files = document.getElementById('fileToUpload').files;
var fd = new FormData();
for (var x = 0; x < files.length; x++) {
    fd.append("fileToUpload[]", files[x]);
}

PHP (uph.php):

To handle multiple files on the server side, modify the PHP script as follows:

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

With these adjustments, the code will iterate over the chosen files, append them to the formData object, and send them to the PHP script for processing. This method allows for the upload and handling of multiple selected files.

The above is the detailed content of How to Upload Multiple Files Using FormData() in JavaScript and PHP?. 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