Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-22 22:48:02
Original
322 people have browsed it

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

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/>';
}
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!