Home  >  Article  >  Web Front-end  >  How to Handle Multiple File Uploads Using formData()?

How to Handle Multiple File Uploads Using formData()?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 20:30:03259browse

How to Handle Multiple File Uploads Using formData()?

Uploading Multiple Files using formData()

Uploading multiple files using the FormData() method requires slightly different syntax than uploading a single file. The original code provided only uploads the first file selected using the files[0] property. To handle multiple file uploads, you need to iterate through the selected files and append each one to the FormData object.

JavaScript:

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

In this revised code, we use files.length to determine the number of files selected and then iterate through the files, appending each one to the FormData object using the "fileToUpload[]" key.

PHP:

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

On the PHP side, you need to modify the code to handle multiple file uploads using the count() function and looping through the files using an index. This will allow you to access and process each uploaded file individually.

The above is the detailed content of How to Handle Multiple File Uploads Using 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