Drag and Drop file upload using Dropzone in Laravel 7

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 the CSRF token for uploading the files.

In this tutorial, I show how you can upload a file using dropzone in Laravel.

Drag and Drop file upload with Dropzone in Laravel 7


Contents

  1. Download
  2. Route
  3. Controller
  4. View
  5. Output
  6. Conclusion

1. Download

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

2. Route

  • Open routes/web.php file.
  • Define 2 routes –
Route::get('/','[email protected]');
Route::post('/users/fileupload/','[email protected]')->name('users.fileupload');
  • The 2nd route is used for Dropzone file upload.

3. Controller

  • Create UsersController Controller.
php artisan make:controller UsersController
  • Open app/Http/Controllers/UsersController.php file.
  • Import Carbon\Carbon.
  • Create two methods –
    • index – Load users.index view.
    • fileupload – This method is used to upload the selected file of Dropzone.

Assign upload location to $destinationPath variable.

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;

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/';

       // 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 = $request->file('file')->getClientOriginalName().time() .'.' . $extension;
         // Uploading file to given path
         $request->file('file')->move($destinationPath, $fileName); 

       }

     }
  }
}

4. View

Create file –

  • Create a new directory users at resources/views/ directory.
  • In resources/views/users/ directory create a new index.blade.php file.

Include CSS and JS –

  • Specify csrf_token() in the <meta >.
  • Include Dropzone CSS and JS files at the <head > section.

Dropzone container –

  • Create <form class='dropzone' >. Pass {{route('users.fileupload')}} in action attribute.

Script –

  • Read CSRF token from <meta > tag and assign in CSRF_TOKEN variable.
  • Disable dropzone auto-discovery by assigning false – Dropzone.autoDiscover = false;.
  • Initialize dropzone on class='dropzone'. Set max upload file size to 3 MB and upload file extensions – jpeg, jpg, png, and pdf.
  • Use dropzone 'sending' event to pass CSRF_TOKEN with formData – formData.append("_token", CSRF_TOKEN).

Completed Code

<!DOCTYPE html>
<html>
  <head>
    <title>Drag and Drop file upload with Dropzone in Laravel 7</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>

5. Output

View Output


6. Conclusion

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

If you found this tutorial helpful then don't forget to share.

17 thoughts on “Drag and Drop file upload using Dropzone in Laravel 7”

  1. you example has this pointing to localhost:8000 what if this is on a server in teh cloud you get to from DNS ? I went through the example and had no idea how ot access it from the url

    Reply
  2. I’m new to laravel, and the above didn’t work. I had to make sure I included the UsersController in the web.php routes. It was throwing error 500. Everything is fine now. Thanks!

    Reply
    • how did you do this? I have the same issue (Error: Target class [UsersController] does not exist.). I am also new to Laravel – would be awesome if you can share some more detailled info like the improved web.php route. Thanks a lot.

      Reply
      • Hi Sophie,
        Check the laravel version using this command – php artisan –version

        If the version is 8 then you need to import the controller in the web.php file –

        use App\Http\Controllers\UsersController;

        You can view this tutorial for reference.

Leave a Comment