Bladephp: Now with 7+ codeigniter, php, and laravel project 7+ php project From $18/Year From Rs. 1000/Year

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

by
Category:php
php ajax javascript jquery html css
How to Create Drag And Drop Image Upload Using jQuery Ajax And PHP

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. You may also like How to Display Text Over Image Using HTML And CSS and Multiple Image Upload in 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();
  }
 }
}
?>

0 Comments


Html code work in comment box


Related Post