Dropzone is easier to add on the page. It allows either uploading 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 7.
Contents
1. Download
- Download Dropzone library from here
- Extract the downloaded files in
public/
folder. - You can also CDN –
<script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script> <link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
2. Route
- Open
routes/web.php
file. - Define 2 routes –
Route::get('/','UsersController@index'); Route::post('/users/fileupload/','UsersController@fileupload')->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.
- index – Load
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 folder
users
atresources/views/
folder. - In
resources/views/users/
folder create a newindex.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')}}
inaction
attribute.
Script –
- Read CSRF token from
<meta >
tag and assign inCSRF_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 passCSRF_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
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.
woooow …. wonderful tutorial … thank you so much .
You’re welcome.
do you have laravel wuth vue dropzone?
Hi Michael,
Currently, I didn’t have a tutorial on this topic. I will try to publish it soon.
OK, thks.
Hello, thanks for this guide.
Got my app working with dropzone.
You’re welcome.
Dropzone in Laravel how to add other fields
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
Host your laravel instance with a dns record, then access it from there.
Wonderful Article!
If anyone want to use dropzone in vue with Laravel then I suggest this video: https://youtu.be/KPYpVdTPUeI
Very informative and step by step video.
Could you add a remove/delete icon on UI which allow to remove it from UI ?
yes, me too. Plx help to confirm us if u can or not. Thank You .
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!
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.
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.
How to use addRemoveLinks to remove file and How to display thumbnail in display view