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

JavascriptJqueryHtmlDrag and-Drop

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChinView Question on Stackoverflow
Solution 1 - JavascriptAlexView Answer on Stackoverflow