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 Development Company | Hire Laravel Developer

Laravel Development Company | Hire Laravel Developer

Get a free quote for custom Laravel Development Services from a trusted Laravel web development company. Hire Laravel Developers now @ best affordable rates

Get a free quote for custom Laravel Development Services from a trusted Laravel web development company. Hire Laravel Developers now at best affordable rates

Laravel Tutorial - Abusing Laravel

Laravel Tutorial - Abusing Laravel

Laravel Tutorial - Abusing Laravel: In this talk, Gustavo takes a look at the importance of Unit Tests and how Dependency Injection, which is often not promoted by Laravel docs, can help to achieve Unit Testing.

In this talk, Gustavo takes a look at the importance of Unit Tests and how Dependency Injection, which is often not promoted by Laravel docs, can help to achieve Unit Testing.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about Laravel

Laravel 5.8 Tutorial for Beginners

Learn GraphQL with Laravel and Vue.js - Full Tutorial

Export or Import of CSV or Excel file in Laravel 5.8 with MySQL

Laravel 5.8 CRUD Tutorial With Example Step By Step

Build RESTful API In Laravel 5.8 Example

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather

Get Weather Data with Laravel Weather. Laravel Weather is a good package which we can use to get weather data. It's a wrapper around Open Weather Map API (Current weather). A wrapper around Open Weather Map API (Current weather)

🌤️ A wrapper around Open Weather Map API (Current weather)

Installation

You can install the package via composer:

source-shell
composer require gnahotelsolutions/laravel-weather
Usage
text-html-php
$weather = new Weather();

// Checking weather by city name
$currentWeatherInGirona = $weather->get('girona,es');

// You can use the city id, this will get you unambiguous results
$currentWeatherInGirona = $weather->find('3121456');

Units

By default the package uses metric for Celsius temperature results, this can be modified using the configuration file or on the fly:

text-html-php
$weather = new Weather();

$currentWeatherInGirona = $weather->inUnits('imperial')->get('girona,es');

Language

By default the package uses es for the description translation, this can be modified using the configuration file or on the fly:

text-html-php
$weather = new Weather();

$currentWeatherInGirona = $weather->inLanguage('en')->get('girona');

Guzzle Client Instance

If you need to use another instance of Guzzle, to modify headers for example:

text-html-php
$weather = new Weather();

$guzzle = $this->getSpecialGuzzleClient();

$currentWeatherInGirona = $weather->using($guzzle)->get('girona');

Testing

source-shell
composer test