HTML provides support for Drag and Drop events. This post discusses how to upload file using drag and drop in HTML ?

The following 4 events are used to identify activity in drag and drop area.

  • dragenter : Fires dragenter event when something enters into drag area
  • dragleave : Fires dragleave event when something leaves from drag area
  • drop : Fires drop event when something is dropped into drag area
  • dragover : Fires dragover event when something moves into drag area

Explanation

Following is the code snippet used in the demo to identify drag and drop events in HTML5.

	
		$(document).ready(function(){
			$("#dropFiles").on('dragenter', function(ev) {
		    	// Entering drop area. Highlight area
		      	$("#dropFiles").addClass("highlightDropArea");
		  	});
		  
		  	$("#dropFiles").on('dragleave', function(ev) {
		    	// Going out of drop area. Remove Highlight
		    	$("#dropFiles").removeClass("highlightDropArea");
		  	});
		  
		  	$("#dropFiles").on('drop', function(ev) {
			    // Dropping files
			    ev.preventDefault();
			    ev.stopPropagation();
			    
			    // iterate through files and upload it on server.
			    if(ev.originalEvent.dataTransfer){
			    	if(ev.originalEvent.dataTransfer.files.length) {
				        var droppedFiles = ev.originalEvent.dataTransfer.files;
				        for(var i = 0; i < droppedFiles.length; i++)
				        {
				          $("#messages").append("
Dropped File "+ droppedFiles[i].name); // Upload droppedFiles[i] to server // $.post(); to upload file to server } } } $("#dropFiles").removeClass("highlightDropArea"); return false; }); $("#dropFiles").on('dragover', function(ev) { ev.preventDefault(); }); });

Demo

See the Pen Drag and Drop file in HTML using JQuery by Hiral Patel (@hiralbest) on CodePen.