JavaScript library Dropzone.js is provide feature to drag and drop files(multiple files) from their computer into form to upload them with preview.
Let’s start to create drag and drop file upload using dropzone js with preview in Laravel 11:
Step 1 – Create File Upload Form
Create a form where users select file for upload to server:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 11 Drag and Drop File Upload Tutorial - ItcodStuff.com</title>
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Include Dropzone.js CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.min.css">
</head>
<body>
<div class="container mt-5">
<h1>Laravel 11 Drag and Drop File Upload Tutorial - ItcodStuff.com</h1>
<form action="{{ route('upload') }}" method="POST" class="dropzone" id="file-upload">
@csrf
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
</div>
<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<!-- Include Dropzone.js CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
</body>
</html>
Step 2 – Add Dropzone.js CDN and Function in Form
<script>
// Initialize Dropzone
Dropzone.options.fileUpload = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
acceptedFiles: ".png, .jpg, .jpeg, .gif", // Allowed file types
init: function() {
this.on("success", function(file, response) {
// Handle successful uploads
console.log(response);
});
}
};
</script>
Step 3 – Create Controller and Handle File Upload
Create a methods in controller file to handle file upload process:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
public function upload(Request $request)
{
$file = $request->file('file');
// Logic to store or process the file
return response()->json(['success' => 'File uploaded successfully']);
}
}
Step 4 – Add Routes
Add routes in web.php file to handle file upload requests:
// routes/web.php
use App\Http\Controllers\FileUploadController;
Route::get('/', function () {
return view('file-upload');
});
Route::post('/upload', [FileUploadController::class, 'upload'])->name('upload');
Step 5 – Test Application
Run application by using the following command:
php artisan serve
Now test your laravel 11 drag and drop multiple file upload application in browser:
http://127.0.0.1:8000/file-form
With just 5 steps you will be able to easily upload multiple files with preview using dropzone js in Laravel 11 application.