75

Is it possible to use jQuery's drop event for dragging files from the desktop?

If so, how do I get the dropped file data?

1

1 Answer 1

164

It's a little messy (you need to handle at least 3 events) but possible.

First, you need to add eventhandlers for dragover and dragenter and prevent the default actions for these events like that:

$('#div').on(
    'dragover',
    function(e) {
        e.preventDefault();
        e.stopPropagation();
    }
)
$('#div').on(
    'dragenter',
    function(e) {
        e.preventDefault();
        e.stopPropagation();
    }
)

It's actually important to call preventDefault on these events, otherwise, some browsers may never trigger the drop event.

Then you can add the drop-handler and access the dropped files with e.originalEvent.dataTransfer.files:

$('#div').on(
    'drop',
    function(e){
        if(e.originalEvent.dataTransfer && e.originalEvent.dataTransfer.files.length) {
            e.preventDefault();
            e.stopPropagation();
            /*UPLOAD FILES HERE*/
            upload(e.originalEvent.dataTransfer.files);
        }
    }
);

Now you are able to drag files from the desktop/explorer/finder in the div and access them.

http://jsfiddle.net/fSA4N/5/

Sign up to request clarification or add additional context in comments.

7 Comments

Why do you need to suppress default dragover and dragenter behavior?
Some browsers do some weird things when you start dragging a file into the browser. It's not really necessary. With these events, you could also add some nice features like highlighting the div where you have to drop the file.
is it possible to somehow use e.originalEvent.dataTransfer.files and set it to file input?
You said "not easy" ...? Your reply solved my same problem instantly! @loostro: what is possble is to have a "global" var called "file", and use $(':file').change() i.c.w. e.target.files[0] (works for me), or maybe $('this').val();
Further to 'some browsers do some weird things': if you miss your drag target with, say, an image file drag, the default behaviour for some browsers e.g. Firefox is to open the file in the window. To circumvent this, bind the document body to the dragover and drop events and cancel them (with preventDefault/stopPropagation).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.