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.
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.
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.
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.
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/>'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With