Reputation: 1864
How can i upload multiple files via drag & drop and browse with ajax? Code below is what i have so far and works great, but allows only 1 file to upload:
This is the html:
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>DROP FILE HERE</p>
<p>or</p>
<p><input class="browse" type="button" value="Browse" onclick="file_explorer();"></p>
<input type="file" id="selectfile">
</div>
</div>
Below is the javascript with ajax i use; :
var fileobj;
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function ajax_file_upload(file_obj) {
if(file_obj != undefined) {
var form_data = new FormData();
form_data.append('file', file_obj);
$.ajax({
type: 'POST',
url: 'ajax.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
//alert(response);
$(".success").html(response);
$('#selectfile').val('');
$('.myFiles').load(document.URL + ' .myFiles');
}
});
}
}
And the php for uploading:
$arr_file_types = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'];
if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
echo "false";
return;
}
move_uploaded_file($_FILES['file']['tmp_name'], '../uploads/'. $_FILES['file']['name']);
echo "File uploaded successfully.<br /><br />";
Upvotes: 1
Views: 2346
Reputation: 1427
It seems you are getting only first file to upload "e.dataTransfer.files[0]". Try to change to this:
function upload_file(e) {
e.preventDefault();
//here you can get all files
for (var i=0; i< e.dataTransfer.files.length;i++){
fileobj = e.dataTransfer.files[i];
ajax_file_upload(fileobj);
}
}
For browsing, i guess the same logic is valid
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
//here you can get all files
for (var i=0; i< e.dataTransfer.files.length;i++){
fileobj = document.getElementById('selectfile').files[i];
ajax_file_upload(fileobj);
}
};
}
If navigation do not work, you can try to reach your element by using event.target https://developer.mozilla.org/en-US/docs/Web/API/Event/target
Upvotes: 2