How to Create Drag And Drop Image Upload Using jQuery Ajax And PHP

HTML Code

<div id="wrapper">
    <input type="file" style="display: none;">
    <div id="drop-area">
     <h3 class="drop-text">Drag and Drop Images Here</h3>
    </div>
</div>

CSS Code

<style>
    #wrapper
    {
     text-align:center;
     margin:0 auto;
     padding:0px;
     width:995px;
    }
    #drop-area
    {
     margin-top:20px;
     margin-left:220px;
     width:550px;
     height:200px;
     background-color:white;
     border:3px dashed grey;
    }
    .drop-text
    {
     margin-top:70px;
     color:grey;
     font-size:25px;
     font-weight:bold;
    }
    #drop-area img
    {
     max-width:200px;
    }
</style>

jQuery Code

<script>
$(document).ready(function()
{
    $("#drop-area").on('dragenter', function (e){
     e.preventDefault();
     $(this).css('background', '#BBD5B8');
    });

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

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

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

function uploadFormData(formData) 
{
    $.ajax({
    url: "upload_file.php",
    type: "POST",
    data: formData,
    contentType:false,
    cache: false,
    processData: false,
    success: function(data){
        $('#drop-area').html(data);
    }});
}
</script>

PHP Code (upload_file.php)

<?php
if(!empty($_FILES)) 
{
 if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
  $sourcePath = $_FILES['userImage']['tmp_name'];
  $targetPath = "images/".$_FILES['userImage']['name'];
  if(move_uploaded_file($sourcePath,$targetPath)) {
  ?>
   <img src="<?php echo $targetPath; ?>">
   <?php
   exit();
  }
 }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *