开发者

HTML5's File API - How to know what's being dragged on?

I've just started working with HTML5's File API. I've been able to mimick imgur's behavior: when a file is being dragged into the document, a big overlay appears with a message to drop to start uploading.

However, I just noticed something: if you drag any element in the page (text, images), the overlay shows up. You can try it on imgur, it's the same thing that happens with my code.

Altough when releasing, nothing ac开发者_Python百科tually happens because the script will check if there are files to upload. My question is, how to know beforehand what's being dragged in the document? At first I thought it was not possible since imgur and all the demos out there have the same issue.

To my surprise, Gmail can detect whether it's a file or just something else that's being dragged on, but it would be fairly impossible to trackback the snippet.

(I can provide code if you want, however it's pretty simple: the events dragenter, dragover and drop are added to the document element and everything is handled as in the demos)

Thanks.

Update

robertc's answer is correct, that seems to be the way to check for Firefox. By trial and error, I've found a way to check with Chrome:

event.originalEvent.dataTransfer.types.indexOf('Files')

It will return -1 if there are no files. So you can now do something like:

try {
    if(event.originalEvent.dataTransfer.types.indexOf('Files') == -1){
        return false;
    }
} catch(E){}

try {
    if(!event.originalEvent.dataTransfer.types.contains("application/x-moz-file")){
        return false;
    }
} catch(E){}

However I don't think that's the best way to test it, but adding both conditionals in the try will not work.


You have to test the drag type in the dragover/dragenter event. In Firefox a file will have type application/x-moz-file so you can do some variation of this:

function checkDrag(event) {
    return event.dataTransfer.types.contains("application/x-moz-file");
}

I'm not sure what the equivalent types are for other browsers.


I use this to ignore dragged URLs, text, etc (non-files) in my handleDrop(event):

if(typeof event.dataTransfer.files == "undefined" || 
     event.dataTransfer.files.length == 0)
        return;

but it doesn't catch folders.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜