Showing posts with label dropzone js. Show all posts
Showing posts with label dropzone js. Show all posts

Sunday, 19 April 2020

Drag and Drop Multiple File upload in Laravel 7 using Dropzone.js



In this tutorial, We have define How can we use Dropzone.js library for drag and drop multiple image file upload in Laravel 7 framework. If you are looking for learn How to upload multiple image using Dropzone.js library with Laravel 7 framework. Then you have come on the right place, where we have make this tutorial in which we have describe step by step tutorial on implementing Dropzone.js library with Laravel 7 framework for upload drag and drop image under Laravel public directory. In this tutorial, we have not only learn you how to upload image in Laravel 7 framework by using Dropzone.js library but also we have describe how to display images from Laravel public directory with remove image link.

Dropzone.js library is the jQuery plugin and by using this plugin we can select image one by one with image preview. By using this plugin, when we have select image from our local computer then first Dropzone.js plugin has display image preview on web page before uploading of image. By using Dropzone plugin, we can validate maximum uploading of image or file, we can define image or extension for validation. Dropzone is very famous, open source library, which we can use at free of cost. This library has provide feature like drag and drop upload multiple files or multiple image with preview of image.

Here we have use Dropzone.js library with Laravel 7 framework and make simple Laravel application for upload multiple file with drag and drop image upload feature. For upload image with preview image in Laravel framework, we have use Dropzone.js library. By using this library we have develop laravel application with drag and drop image upload feature. Once image has been uploading in Laravel public folder, then after we have fetch image from Laravel public folder and display on web page. At the last of tutorial, you can also find how to delete or remove image from Laravel public folder in Laravel framework. In this tutorial, we have use Ajax with Laravel 7 framework for fetch and display image from Laravel public directory and for delete or remove image in Laravel framework. Below you can find step by step process for how to use Dropzone.js library in Laravel 7 framework.

  1. Install Laravel 7 framework
  2. Create Controller in Laravel 7
  3. Create View File in Laravel 7
  4. Set Route
  5. Run Laravel 7 Application
.




Step1 - Install Laravel 7 framework


If you have decided to use Laravel framework for web development. Then first we have make download and install Laravel 7 framework. For this we have to go command prompt and first run composer, this is because Laravel framework dependency has been manage by composer. After this we have go directory in which we want to download and install Laravel 7 framework and write following command.


composer create-project --prefer-dist laravel/laravel laravel7


This command will download and install Laravel 7 framework in define directory.




Step2 - Create Controller in Laravel 7


After download and installing of Laravel 7 framework, In this post first we want to make controller for handle http request. In Laravel 7 framework controller class has been store in app/Http/Controllers folder. All controller file will be store under this folder. For create new controller class, we have to go command prompt and write following command.


php artisan make:controller DropzoneController


This command will make DropzoneController.php class in app/Http/Controllers folder. For upload drag and drop image upload in Laravel 7 framework using Dropzone.js plugin, we have make following method in this controller class.

index() - This is root method of this controller class, and it will load dropzone.blade.php view file in browser.
upload(Request $request) - This method will received upload image request from Dropzone.js plugin. This method will upload image in Laravel public directory.
fetch() - This method will received ajax request for fetch images from Laravel public folder and send image data to ajax request which will be display on web page.
delete(Request $request) - This method also received ajax request for delete or remove image from Laravel public folder. This method will received image name and based on image name it will delete or remove image from Laravel public directory.

app/Http/Controllers/DropzoneController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DropzoneController extends Controller
{
    function index()
    {
     return view('dropzone');
    }

    function upload(Request $request)
    {
     $image = $request->file('file');

     $imageName = time() . '.' . $image->extension();

     $image->move(public_path('images'), $imageName);

     return response()->json(['success' => $imageName]);
    }

    function fetch()
    {
     $images = \File::allFiles(public_path('images'));
     $output = '<div class="row">';
     foreach($images as $image)
     {
      $output .= '
      <div class="col-md-2" style="margin-bottom:16px;" align="center">
                <img src="'.asset('images/' . $image->getFilename()).'" class="img-thumbnail" width="175" height="175" style="height:175px;" />
                <button type="button" class="btn btn-link remove_image" id="'.$image->getFilename().'">Remove</button>
            </div>
      ';
     }
     $output .= '</div>';
     echo $output;
    }

    function delete(Request $request)
    {
     if($request->get('name'))
     {
      \File::delete(public_path('images/' . $request->get('name')));
     }
    }
}
?>


Step3 - Create View File in Laravel 7


In Laravel framework, View file has been used for display HTML output in browser. In this file we have include jQuery, Bootstrap and Dropzone.js library url. In this file we have use Dropzone.js plugin for drag and drop upload image file in Laravel framework. Once image has been uploaded, then in this file we have write Ajax request for fetch images from Laravel public directory and display on web page. And Same way for delete image from Laravel public folder, here also we have write Ajax request for delete image from Laravel public directory. Below you can find source code of dropzone.blade.php file.

resources/views/dropzone.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Image Upload in Laravel using Dropzone</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <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-fluid">
      <br />
    <h3 align="center">Image Upload in Laravel using Dropzone</h3>
    <br />
        
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Select Image</h3>
        </div>
        <div class="panel-body">
          <form id="dropzoneForm" class="dropzone" action="{{ route('dropzone.upload') }}">
            @csrf
          </form>
          <div align="center">
            <button type="button" class="btn btn-info" id="submit-all">Upload</button>
          </div>
        </div>
      </div>
      <br />
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Uploaded Image</h3>
        </div>
        <div class="panel-body" id="uploaded_image">
          
        </div>
      </div>
    </div>
 </body>
</html>

<script type="text/javascript">

  Dropzone.options.dropzoneForm = {
    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();
        }
        load_images();
      });

    }

  };

  load_images();

  function load_images()
  {
    $.ajax({
      url:"{{ route('dropzone.fetch') }}",
      success:function(data)
      {
        $('#uploaded_image').html(data);
      }
    })
  }

  $(document).on('click', '.remove_image', function(){
    var name = $(this).attr('id');
    $.ajax({
      url:"{{ route('dropzone.delete') }}",
      data:{name : name},
      success:function(data){
        load_images();
      }
    })
  });

</script>



Step4 - Set Route


In next step we have to set route of all DropzoneController.php controller method. For this we have to open routes/web.php file and in this file we have to set route of all controller method.

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

Route::get('dropzone', 'DropzoneController@index');

Route::post('dropzone/upload', 'DropzoneController@upload')->name('dropzone.upload');

Route::get('dropzone/fetch', 'DropzoneController@fetch')->name('dropzone.fetch');

Route::get('dropzone/delete', 'DropzoneController@delete')->name('dropzone.delete');


Step5 - Run Laravel 7 Application


Once your all code is ready and have you set route of all controller method, then at last we have to run Laravel 7 server. For this we have to go command prompt and write following command.


php artisan serve


This command will start Laravel 7 server and return you base url of your Laravel 7 application. If you want to run above code, you have to write following url in browser.


http://127.0.0.1:8000/dropzone


So, this is complete step by step process of integrating Dropzone.js plugin in Laravel 7 framework for drag and drop upload multiple images in Laravel 7 public directory and then after fetch image from Laravel 7 framework public folder and display on web page and lastly how to delete or remove image from Laravel framework public directory using Ajax.

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;

?>