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

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

Patricia Arquette
Release: 2024-10-22 21:32:29
Original
774 people have browsed it

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

Uploading Multiple Files with formData()

When working with file uploads in JavaScript and PHP, it's common to face scenarios where multiple files need to be transmitted simultaneously. The FormData interface offers a convenient method for achieving this. However, the default behavior of selecting only the first file in an input field may seem limiting.

How to Upload Multiple Chosen Files

To overcome this limitation, the JavaScript code must iterate through all selected files and append them to the FormData object. The following code demonstrates this:

<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

In this code, we retrieve all chosen files from the input field and iterate through them, appending each file to the FormData object with the key fileToUpload[]. This technique allows us to upload multiple files in a single Ajax request.

Handling Multiple Files in PHP

On the server side, PHP can receive the uploaded files in an array. To access individual files, use the array syntax:

<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

This code iterates through the uploaded files and prints their names for demonstration purposes. You can use this array to perform further processing, such as saving the files to a specific location or performing validations.

By following these steps, it becomes possible to upload multiple files simultaneously using formData() and handle them effectively in PHP.

The above is the detailed content of How to Upload Multiple Files Simultaneously with 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!