jQuery Drag and Drop Image Upload

by Vincy. Last modified on October 14th, 2022.

In this tutorial, we are going to upload image files by drag and drop from source to destination. We have seen already about how to do drag and drop element by using jQuery.

In this tutorial, we are having jQuery event handlers which will be triggered based on the drag-drop events. On dropping image files, an AJAX request will be called for a PHP file for uploading dropped images.

View Demo

jQuery Drag Drop Event Handlers

This code contains jQuery drag-drop event handlers which will be called on dragging image files.

drag and drop image upload jquery

$(document).ready(function() {
    $("#drop-area").on('dragenter', function (e){
    e.preventDefault();
    });

    $("#drop-area").on('dragover', function (e){
    e.preventDefault();
    });

    $("#drop-area").on('drop', function (e){
    e.preventDefault();
    var image = e.originalEvent.dataTransfer.files;
    createFormData(image);
    });
});

Create jQuery Form-Data Object

On the drop event, we are creating jQuery FormData object with dropped image files. This object will be sent to a PHP page to upload images via AJAX.

function createFormData(image) {
	var formImage = new FormData();
	formImage.append('userImage', image[0]);
	uploadFormData(formImage);
}

function uploadFormData(formData) {
	$('#loader-icon').show();
	$.ajax({
		url: "upload-ajax.php",
		type: "POST",
		data: formData,
		contentType: false,
		cache: false,
		processData: false,
		success: function(data) {
			$('#drop-area').append(data);
			$('#loader-icon').hide()
			$('#success-message-info').html("Added Successfully");
			$('#success-message-info').css("display", "inline-block");
		}
	});
}

PHP Image Upload

This PHP code is similar as we have seen in previous AJAX image upload tutorials.

<?php
if (is_array($_FILES)) {
    if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {
        $sourcePath = $_FILES['userImage']['tmp_name'];
        $targetPath = "uploads/" . $_FILES['userImage']['name'];
        if (move_uploaded_file($sourcePath, $targetPath)) {
            ?>
<img src="<?php echo $targetPath; ?>" width="100px" height="100px"
    hspace=15 accept=".jpg, .jpeg, .png, .gif" />
<?php
        }
    }
}
?>

HTML Image Drop Area

This HTML code is used for creating drop area to drag and upload image files.

<div class="phppot-container">
    <div id="drop-area">
        <h3 class="drop-text">Drop images here to upload</h3>
    </div>
    <div id="loader-icon">
        <img src="loader.gif" />
    </div>
    <div id="success-message-info" class="message success display-none"></div>
</div>

View DemoDownload

↑ Back to Top

Share this page