In this example we will show Drag and Drop File Upload using Dropzone in Laravel. we will explain step by step file upload in laravel using dropzone.
In this post we simply laravel file upload using Dropzone. Dropzone is mostly used in drag and drop file. Using dropzone you can simply upload file in laravel. In Laravel, need to also pass the CSRF token for uploading the files.
Step 1: Add route
In this step we will create routes for file upload using dropzone.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\UserController; Route::get('/',[UserController::class,'index']); Route::post('/users/fileupload/',[UserController::class,'fileupload'])->name('users.fileupload');
Step 2: Create controller
In this step we will create UserController.php file. In this file we will write laravel file upload code.
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index(){ return view('users'); } public function fileupload(Request $request){ if($request->hasFile('file')) { $destinationPath = 'files/'; $extension = $request->file('file')->getClientOriginalExtension(); $validextensions = array("jpeg","jpg","png","pdf"); if(in_array(strtolower($extension), $validextensions)){ $fileName = time() . $request->file('file')->getClientOriginalName(); $request->file('file')->move($destinationPath, $fileName); } } } }
Step 3: Create view
In this step we will create users.blade.php file for dropzone file upload code.
<!DOCTYPE html> <html> <head> <title>Drag and Drop file upload with Dropzone in Laravel 7</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta name="csrf-token" content="{{ csrf_token() }}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></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>
I hope you understand of drag and drop file upload using dropzone in laravel and it can help you..