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.


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. 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; 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 = $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</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


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.

Related Posts