1

Is there a way to abort/cancel file transfer after onDrop event in Javascript, if invalid file type is selected/dropped onto the drop area?

For instance, if only .jpg, .png file formats are allowed, but the user drags and drops onto the drop area a file that has a *.gif extension I would like to cancel automatically sending/uploading data to the server and notify that an invalid file format is selected?

simple example

div = document.getElementById('div');
div.ondragover = function(event){

   div.ondrop = function(event){

if(event.dataTransfer.files[0].type == 'gif'){
    abort/cencel upload here
    }
    } 


  return false;//cancelling ondragover to allow ondrop event 

    }
user1190478
  • 119
  • 1
  • 11

1 Answers1

0

So if you are using html + js native event to capture the drop.

Here's how to get the info:

event.dataTransfer.files[0].name // to get the file name
event.dataTransfer.files[0].size // to get the file size
event.dataTransfer.files[0].type // to get the file type

Filter type:

First, you need to cancel the default behavior to prevent uploading.

event.preventDefault();

for IE use this

    if (event.preventDefault) 
    { 
      event.preventDefault(); 
    } 
    else 
     { 
       event.returnValue = false;
     }

Then you can analyze your data.

if(event.dataTransfer.files[0].type == 'gif')
{
    //show message
}

And then you can proceed with uploading using e.g. ajax

var xhr = new XMLHttpRequest();
xhr.open("POST", "receivefile.php", true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);

Full Article Source.

Community
  • 1
  • 1
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38
  • Yes, I'm using plain Javascript. event.preventDefault() for all browsers, or just for IE only? – user1190478 Jan 26 '14 at 19:10
  • I'm using event.preventDefault() for IE only and return false for other browsers. I was just going to write that and saw your updated answer. Tried it and it worked. Thank you! – user1190478 Jan 26 '14 at 19:17
  • Actually, I tried the implementation you offered before asking this question, but I put event.preventDefault/return false in the wrong place. That's why it didn't work at first. After reading your answer, changed the place and it worked (: – user1190478 Jan 26 '14 at 19:21