I am trying to make an upload form with AJAX/jQuery. The problem is i can't upload multiple files from a single input. With this code I can upload 1 file:
HTML:
<form name="myform" id="myform" enctype="multipart/form-data">
<input name="file[]" type="file" multiple />
<input type="button" value="Upload" />
</form>
jQuery:
$(document).ready(function(){
$(':button').click(function(){
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
dataType:"json",
async: true,
success: function(data) {
console.log(data.Result);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
I changed the formData
part to this:
var formData = new FormData($('input[name^="file"]'));
$.each($('input[name^="file"]')[0].files, function(i, file){
formData.append(i, file);
});
the PHP part:
foreach($_FILES as $index => $file)
{
// for easy access
$fileName = $file['name'];
// for easy access
$fileTempName = $file['tmp_name'];
// check if there is an error for particular entry in array
if(!empty($file['error'][$index]))
{
// some error occurred with the file in index $index
// yield an error here
return false;
}
// check whether file has temporary path and whether it indeed is an uploaded file
if(!empty($fileTempName) && is_uploaded_file($fileTempName))
{
// move the file from the temporary directory to somewhere of your choosing
move_uploaded_file($fileTempName, ROOT_DIR . '/uploads/xPhoto/' . $fileName);
// mark-up to be passed to jQuery's success function.
echo '<p>Click <strong><a href="uploads/' . $fileName . '" target="_blank">' . $fileName . '</a></strong> to download it.</p>';
}
}
So my question is, how can I upload multiple files with a single input?
you may need to include an index on file:
formData.append(i, file[i]);
This works for me. Let's you upload multiple files from single input. All accessible from the $_FILES
global in php.
var formData = new FormData();
var files = $('#files_input').prop('files');
$.each(files, function(i, file) {
formData.append("file_" + i, file);
});