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!