Drag and Drop file upload using Dropzone in Laravel

Drag and Drop file upload using Dropzone in Laravel

Dropzone is easier to add on the page.It allows either uploads the file by drag & drop or file browse. It displays file preview after upload.In Laravel, need to also pass CSRF token for uploading the files.In this tutorial, I show how you can upload a file using dropzone in Laravel.

1. Download

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

    2. Route

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.
Route::get('/','[email protected]');
Route::post('/users/fileupload/','[email protected]')->name('users.fileupload');
  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

    3. Controller

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.
php artisan make:controller UsersController
  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

Assign upload location to $destinationPath variable. Create a directory if not exists.

Get the file extension and initialize valid file extension in $validextensions Array.

Check the file extension is exists in $validextension Array. If exists then rename the file and upload it.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Carbon\Carbon;

class UsersController extends Controller {

  public function index(){
    return view('users.index');
  }

  /*
  File upload
  */ 
  public function fileupload(Request $request){

     if($request->hasFile('file')) {

       // Upload path
       $destinationPath = 'files/';

       // Create directory if not exists
       if (!file_exists($destinationPath)) {
          mkdir($destinationPath, 0755, true);
       }

       // Get file extension
       $extension = $request->file('file')->getClientOriginalExtension();

       // Valid extensions
       $validextensions = array("jpeg","jpg","png","pdf");

       // Check extension
       if(in_array(strtolower($extension), $validextensions)){

         // Rename file 
         $fileName = str_slug(Carbon::now()->toDayDateTimeString()).rand(11111, 99999) .'.' . $extension;

         // Uploading file to given path
         $request->file('file')->move($destinationPath, $fileName); 

       }

     }
  }
}

4. View

Create file –

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

Include CSS and JS –

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

Dropzone container –

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

Script –

  • Download Dropzone library from here
  • Extract the downloaded files in public/ directory.

Completed Code

<!DOCTYPE html>
<html>
  <head>
    <title>Drag and Drop file upload with Dropzone in Laravel</title>

    <!-- Meta -->
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="{{asset('dropzone/dist/min/dropzone.min.css')}}">

    <!-- JS -->
    <script src="{{asset('dropzone/dist/min/dropzone.min.js')}}" type="text/javascript"></script>

  </head>
  <body>

    <div class='content'>
      <!-- Dropzone -->
      <form action="{{route('users.fileupload')}}" class='dropzone' >
      </form> 
    </div> 

    <!-- Script -->
    <script>
    var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').getAttribute("content");

    Dropzone.autoDiscover = false;
    var myDropzone = new Dropzone(".dropzone",{ 
        maxFilesize: 3,  // 3 mb
        acceptedFiles: ".jpeg,.jpg,.png,.pdf",
    });
    myDropzone.on("sending", function(file, xhr, formData) {
       formData.append("_token", CSRF_TOKEN);
    }); 
    </script>

  </body>
</html>

6. Conclusion

You need to also pass CSRF token to upload the file using Dropzone. For this explicitly initialize dropzone and pass the token.

Recommended Reading

Create a Laravel Vue Single Page App

Laravel Repository Pattern Implementation

Laravel 6 Release New Features and Upgrade

Instructions to Create your first Laravel package

Build a simple blog + multiple image upload with Laravel & Vue

How to set lifetime expiration time of passport access token in Laravel

Upgrading Laravel To 6.0 From 5.8

Laravel Custom Casts Package

Putting a Laravel App into Production

laravel

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Php how to delete multiple rows through checkbox using ajax in laravel

In this article i will let you know to delete multiple rows through checkbox using ajax in laravel and before delete we will give a confirmation message.

How to Hire Laravel Developers and How Much Does It Cost.

Want to make the most out of the latest Laravel technology? Here is your guide on how to hire the best Laravel developer, and at the right price. 

How to perform migration rollback in laravel

Sometimes we need to rollback one specific migration. Here, in this article we will discuss about the migration rollback in laravel.

5 Laravel’s Hidden Gems

Spread the love1. Stop on first validation error By default, Laravel will check for all validation rules and return a list of errors. But if you want to stop this process after first validation failure, that’s how you can achieve…Read More→

How to validate mobile phone number in laravel with example

Data validation is a very important thing for a web application. In this article i will let you know how to validate mobile phone number in laravel.