<h2>Handling Multiple File Uploads with formData()</h2>
When working with file inputs, it's often necessary to handle multiple file uploads. The <pre>formData()</pre> method can be used for this purpose, allowing you to send multiple files in a single request.
<h3>Initial Attempt</h3>
In JavaScript, a common approach is:
<pre>
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
</pre>
However, this code only handles the first selected file.
<h3>Solution: Iterating Through Files</h3>
To enable multiple file uploads, you need to iterate through all the selected files:
<pre>
var files = document.getElementById('fileToUpload').files;
for (var x = 0; x < files.length; x++) {
fd.append("fileToUpload[]", files[x]);
}
</pre>
<h3>Server-Side Handling (PHP)</h3>
On the server-side, you can then handle the multiple files like this:
<pre>
$count = count($_FILES'fileToUpload');
for ($i = 0; $i < $count; $i++) {
echo 'Name: ' . $_FILES['fileToUpload']['name'][$i] . '<br/>';
}
</pre>
By following these steps, you can efficiently process multiple file uploads using <pre>formData()</pre> and handle the files accordingly on the server-side.
Отказ от ответственности: Все предоставленные ресурсы частично взяты из Интернета. В случае нарушения ваших авторских прав или других прав и интересов, пожалуйста, объясните подробные причины и предоставьте доказательства авторских прав или прав и интересов, а затем отправьте их по электронной почте: [email protected]. Мы сделаем это за вас как можно скорее.
Copyright© 2022 湘ICP备2022001581号-3