Home >Web Front-end >JS Tutorial >How Can I Handle Multiple File Uploads with formData()?

How Can I Handle Multiple File Uploads with formData()?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-22 23:57:29285browse

How Can I Handle Multiple File Uploads with formData()?

Handling Multiple File Uploads with formData()

When working with file inputs, it's often necessary to handle multiple file uploads. The

formData()
method can be used for this purpose, allowing you to send multiple files in a single request.

Initial Attempt

In JavaScript, a common approach is:

<br>fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);<br>

However, this code only handles the first selected file.

Solution: Iterating Through Files

To enable multiple file uploads, you need to iterate through all the selected files:

<br>var files = document.getElementById('fileToUpload').files;<br>for (var x = 0; x < files.length; x  ) {</p>
<pre class="brush:php;toolbar:false">fd.append("fileToUpload[]", files[x]);

}

Server-Side Handling (PHP)

On the server-side, you can then handle the multiple files like this:

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

By following these steps, you can efficiently process multiple file uploads using

formData()
and handle the files accordingly on the server-side.

The above is the detailed content of How Can I Handle Multiple File Uploads with formData()?. 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