Reputation: 121
I have a bit of html with an area where a user can drag and drop files to upload. Nested within, is a "browse for files" button that clicks()
a hidden file input should they choose the traditional upload method. Everything works well thus far with the exception that if a user drags and drops multiple files (more than one), it uploads each of them twice (3 dropped files uploads 6 files). It does not do this if the user uploads via the browse for files button, so I've narrowed it down to my on ondrop
function and included that below. I can post additional code if the problem isn't in this code block.
Update: I logged my variable droppedfile
to the console once before the for
loop and once after and noticed that when logged after the for loop and 2 files were dropped, the variable contained 2 fileLists and each list contained both of the files (making 4 uploads). How is my for
loop altering my variable??
dropzone.ondrop = function(e){
e.preventDefault();
this.className = 'dropzone';
var droppedfile = e.target.files || e.dataTransfer.files;
for (i=0; i < droppedfile.length; i++) {
if(droppedfile[i].type != "text/plain" && droppedfile[i].type != "application/pdf" && droppedfile[i].type != "application/msword"){
alert(droppedfile[i].type + " file types are not allowed.");
}else{
uploadButton.innerHTML = 'Uploading...';
//calls a function that assigns the file to a new formdata obj and sends via ajax
upload(droppedfile);
}
}
}
Upvotes: 0
Views: 50
Reputation: 142
The problem occurs because you are uploading both the files each time the for loop is executed. Replace
upload(droppedfile);
witn
upload(droppedfile[i]);
Alternatively You can ensure all files are valid before uploading
var valid=true;
for (i=0; i < droppedfile.length; i++) {
if(droppedfile[i].type != "text/plain" && droppedfile[i].type != "application/pdf" && droppedfile[i].type != "application/msword"){
alert(droppedfile[i].type + " file types are not allowed.");
valid=false;
}
}
if(valid) {
uploadButton.innerHTML = 'Uploading...';
upload(droppedfile);
}
Upvotes: 1