micha
micha

Reputation: 371

Check if drag / drop content is image

I want to check wether the content dragged/dropped onto an area is an image or not. My Code is working in Chrome and Firefox, but not in Safari. I guess it's because Safari has no dataTransfer type text/html for images. Is there a workaround for Safari?

document.addEventListener( 'drop', function( e ) {      
    var contentHtml;        
    if( e.dataTransfer ){           
        contentHtml = (e.originalEvent || e).dataTransfer.getData('text/html');
        if($(contentHtml).is('img')){
            // do some things, then let the standard drop happen
            return true;
        } else {
            // do other things, prevent drop
            return false;
        }
    }
});

Upvotes: 3

Views: 2927

Answers (1)

twernt
twernt

Reputation: 20601

You can use the DataTransfer.files property to get the dropped file's mime type and check it against a known list of allowable image types.

In this snippet, I had to disable to default dragover event handling on the document to prevent the browser from just displaying the image before I was able to inspect the DataTransfer object.

document.addEventListener('dragover', function(e) {
  e.preventDefault();
})

document.addEventListener('drop', function(e) {
  // set your image types
  var imageTypes = ['image/png', 'image/gif', 'image/bmp', 'image/jpeg'];
  if (e.dataTransfer && e.dataTransfer.files) {
    // e.dataTransfer.files is a FileList
    // e.dataTransfer.files[0].type is a Blob.type
    var fileType = e.dataTransfer.files[0].type;
    if (imageTypes.includes(fileType)) {
      window.alert('dropped file is an image');
    } else {
      window.alert('dropped file is not an image');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Here are some links to the related documentation on MDN:

Upvotes: 5

Related Questions