Reputation: 1895
I am building a simple HTML image uploader. The user can select many images using a file input, and for each image a preview is created.
To send the images to the server I was thinking about attaching an input
to each image so that they are automatically sent when the form is submitted.
An element would look like this:
<div>
<input type="file" class="hidden" name="model[images][]">
<img src="base 64 image">
</div>
The problem is that of course I can't set an arbitrary file for the file input, so what's the simplest solution to send many files from the same form without using a single input?
Upvotes: 0
Views: 77
Reputation: 136608
In modern browsers, you can use the FormData object and its append
method :
var input = document.querySelector('input');
var formdata = new FormData();
var nb = 0;
input.onchange= function(e){
// since we can't write in a fileList, we have to add an index so our server can access each files
formdata.append('file_'+nb++, this.files[0], this.files[0].name);
// we also need to keep track of this index
formdata.append('file_count', nb);
}
function sendToServer(){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'script.php');
xhr.send(formdata);
}
Then in script.php
$file_count = $_POST['file_count'];
for($i=0; $i<$file_count; $i++){
// Do whatever with your files
echo $_FILES['file_'.$i]['name'];
}
Upvotes: 1