Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading multiple files using formData()

var fd = new FormData(); fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]); var xhr = new XMLHttpRequest(); xhr.open("POST", "uph.php"); xhr.send(fd); 

uph.php:

var_dump($_FILES['fileToUpload']); 

This works, but obviously for the files[0] only. How to get this working for chosen file?

I tried removing the [0], but it didn't work.

like image 611
jaanisk Avatar asked Oct 20 '12 14:10

jaanisk


People also ask

Can you upload multiple files using FormData in React?

How to Upload Multiple Files in React using FormData. When we need to upload multiple files using Fetch, we have to use a new type of object called FormData. FormData allows us to append multiple key/value pairs onto the object. After we're done appending, we then pass it to the POST request's body.

What is the easiest way to upload single or multiple files with FormData?

Uploading Multiple Files const uploadFile = (files) => { console. log("Uploading file..."); const API_ENDPOINT = "https://file.io"; const request = new XMLHttpRequest(); const formData = new FormData(); request. open("POST", API_ENDPOINT, true); request. onreadystatechange = () => { if (request.

How do you append files in input type file multiple before uploading?

You could add a new <input type="file"> whenever you finished uploading the previous files and hide the previous input. This way you keep adding a new input every time you want to add more files and prevent the previous input from being overwritten.


1 Answers

You have to get the files length to append in JS and then send it via AJAX request as below

//JavaScript  var ins = document.getElementById('fileToUpload').files.length; for (var x = 0; x < ins; x++) {     fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]); }  //PHP $count = count($_FILES['fileToUpload']['name']); for ($i = 0; $i < $count; $i++) {     echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'<br/>'; } 
like image 184
Rowan San Avatar answered Sep 23 '22 15:09

Rowan San