Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...