Home > Article > Web Front-end > How to Upload Multiple Files Using FormData() and XMLHttpRequest
Uploading Multiple Files with formData()
The code snippet provided allows you to upload a single file using the FormData() interface and XMLHttpRequest. To enable the upload of multiple files, however, the approach needs to be modified.
JavaScript:
Remove the [0] index from the append statement and use a loop to iterate through the selected files. The files.length property determines the number of files chosen.
<code class="javascript">var files = document.getElementById('fileToUpload').files; for (var x = 0; x < files.length; x++) { fd.append("fileToUpload[]", files[x]); }
PHP:
On the server-side, retrieve the uploaded files using the following code:
<code class="php">$count = count($_FILES['fileToUpload']['name']); for ($i = 0; $i < $count; $i++) { echo 'Name: ' . $_FILES['fileToUpload']['name'][$i] . '<br/>'; }</code>
You can use this method to upload multiple files with individual names and process them on the server as needed.
The above is the detailed content of How to Upload Multiple Files Using FormData() and XMLHttpRequest. For more information, please follow other related articles on the PHP Chinese website!