Thursday 19 July 2018

Dropzone.js with PHP for Upload File



If you are looking for web tutorial on how to implement Dropzone.js library in your existing PHP web application, then this post will help a lot. Using this tutorial you can easily implement Dropzone.js library with you PHP application. If in you PHP application you have file upload feature then by using this library you can give stylish looks to your file upload feature. Dropzone.js library will also help you to make drag and drop file upload feature very easily with your PHP script. So, by using this tutorial you can learn how to use Dropzone.js library for file upload with single or multiple drag and drop file on server using PHP script.

Dropzone.js is a javascript library and this library is not depend on any another library like jquery. Most of plugin are depends on jquery library but this is not depend on any other library, it can work independently with any script and on any browser. This is light weight javascript library help us to make drag and drop file upload very simply. This library also handle validation library file type, file size and many more. We can also use Dropzone.js library for simple file upload also. By using DropzoneJS with PHP, we can easily implement drag and drop file upload feature in our existing website. DropzoneJS is an open source library which provide us drag and drop file uploads with live image preview on web page before upload image to server. It is a very lightweight library and it does not depends on any other library like jquery and it has not handle files upload to server. So, here we have use PHP script for upload file to server using DropzoneJS library.






In this post we have simply use Dropzone.js library with PHP from image upload to server. For this first we have import Dropzone css file and javascript library file in our index page.


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>


After this we need to write form tag without any form elements, because this library handle other request. Under this
tag we need to write attribute like action, class and id. Here action attribute has defines the actions to upload file to server side and .dropzone class identifier of the Dropzone library.



<form action="upload.php" class="dropzone" id="dropzoneFrom">

</form>


Then after we have to write javascript code for initialiaze DropzoneJS library on
with id #dropzoneForm attribute. Here we have set options of this library like image validation using acceptedFiles:".png,.jpg,.gif,.bmp,.jpeg", option. Here we have disabled immediate upload image to server by using this autoProcessQueue: false, option. Under init() function we have define button click event, so when we have click on button then image will be upload to server. After upload of image we want to clear Drag and drop area, so we have define code under "complete" stage of DropzoneJS library. Whole code you can fine below.



Dropzone.options.dropzoneFrom = {
  autoProcessQueue: false,
  acceptedFiles:".png,.jpg,.gif,.bmp,.jpeg",
  init: function(){
   var submitButton = document.querySelector('#submit-all');
   myDropzone = this;
   submitButton.addEventListener("click", function(){
    myDropzone.processQueue();
   });
   this.on("complete", function(){
    if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
    {
     var _this = this;
     _this.removeAllFiles();
    }
    list_image();
   });
  },
 };







For display uploaded image on webpage after uploading complete, for this we have make on function, this function will fetch all images from upload folder and display on web page.


function list_image()
 {
  $.ajax({
   url:"upload.php",
   success:function(data){
    $('#preview').html(data);
   }
  });
 }



Same way we want to remove any image from server side, for this also we have define one remove button with each image. We have to click on that remove button and image will be deleted from folder and after this it will display remaining images on web page.


$(document).on('click', '.remove_image', function(){
  var name = $(this).attr('id');
  $.ajax({
   url:"upload.php",
   method:"POST",
   data:{name:name},
   success:function(data)
   {
    list_image();
   }
  })
 });


Below code is used for server side upload image, fetch image from folder and remove image from server.


<?php

//upload.php

$folder_name = 'upload/';

if(!empty($_FILES))
{
 $temp_file = $_FILES['file']['tmp_name'];
 $location = $folder_name . $_FILES['file']['name'];
 move_uploaded_file($temp_file, $location);
}

if(isset($_POST["name"]))
{
 $filename = $folder_name.$_POST["name"];
 unlink($filename);
}

$result = array();

$files = scandir('upload');

$output = '<div class="row">';

if(false !== $files)
{
 foreach($files as $file)
 {
  if('.' !=  $file && '..' != $file)
  {
   $output .= '
   <div class="col-md-2">
    <img src="'.$folder_name.$file.'" class="img-thumbnail" width="175" height="175" style="height:175px;" />
    <button type="button" class="btn btn-link remove_image" id="'.$file.'">Remove</button>
   </div>
   ';
  }
 }
}
$output .= '</div>';
echo $output;

?>


So, this step by step process for how to use Dropzone.js with PHP, if you have any query about this post tutorial or script you can feel free to comment below in comment box. Below you can find complete source code.

index.php



<?php
//index.php

?>
<!DOCTYPE html>
<html>
 <head>
  <title>How to Upload a File using Dropzone.js with PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>        
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">How to Upload a File using Dropzone.js with PHP</h3>
   <br />
   
   <form action="upload.php" class="dropzone" id="dropzoneFrom">

   </form>
   
    
   </form>
   <br />
   <br />
   <div align="center">
    <button type="button" class="btn btn-info" id="submit-all">Upload</button>
   </div>
   <br />
   <br />
   <div id="preview"></div>
   <br />
   <br />
  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 
 Dropzone.options.dropzoneFrom = {
  autoProcessQueue: false,
  acceptedFiles:".png,.jpg,.gif,.bmp,.jpeg",
  init: function(){
   var submitButton = document.querySelector('#submit-all');
   myDropzone = this;
   submitButton.addEventListener("click", function(){
    myDropzone.processQueue();
   });
   this.on("complete", function(){
    if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
    {
     var _this = this;
     _this.removeAllFiles();
    }
    list_image();
   });
  },
 };

 list_image();

 function list_image()
 {
  $.ajax({
   url:"upload.php",
   success:function(data){
    $('#preview').html(data);
   }
  });
 }

 $(document).on('click', '.remove_image', function(){
  var name = $(this).attr('id');
  $.ajax({
   url:"upload.php",
   method:"POST",
   data:{name:name},
   success:function(data)
   {
    list_image();
   }
  })
 });
 
});
</script>


upload.php



<?php

//upload.php

$folder_name = 'upload/';

if(!empty($_FILES))
{
 $temp_file = $_FILES['file']['tmp_name'];
 $location = $folder_name . $_FILES['file']['name'];
 move_uploaded_file($temp_file, $location);
}

if(isset($_POST["name"]))
{
 $filename = $folder_name.$_POST["name"];
 unlink($filename);
}

$result = array();

$files = scandir('upload');

$output = '<div class="row">';

if(false !== $files)
{
 foreach($files as $file)
 {
  if('.' !=  $file && '..' != $file)
  {
   $output .= '
   <div class="col-md-2">
    <img src="'.$folder_name.$file.'" class="img-thumbnail" width="175" height="175" style="height:175px;" />
    <button type="button" class="btn btn-link remove_image" id="'.$file.'">Remove</button>
   </div>
   ';
  }
 }
}
$output .= '</div>';
echo $output;

?>

11 comments: