How to use jQuery's drop event to upload files dragged from the desktop?

63,142

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/

Share:
63,142
Chin
Author by

Chin

Updated on July 05, 2022

Comments

  • Chin
    Chin almost 2 years

    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?

  • Chris Martin
    Chris Martin over 11 years
    Why do you need to suppress default dragover and dragenter behavior?
  • Alex
    Alex over 11 years
    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.
  • ioleo
    ioleo over 11 years
    is it possible to somehow use e.originalEvent.dataTransfer.files and set it to file input?
  • Leo
    Leo over 11 years
    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();
  • Zain Ali
    Zain Ali over 9 years
    @Chris By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default handling of the element. This is done by calling the event.preventDefault()
  • David G
    David G over 9 years
    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).
  • Hasse Björk
    Hasse Björk over 8 years
    Here is an example how it works and put together for you!