How To Drag And Drop File Upload In Laravel 11

In Laravel, implementing drag and drop file upload functionality can be accomplished using various frontend libraries like Dropzone js, Filepond, or simply utilizing HTML5’s native drag and drop API. Here’s a guide on how to achieve this with Dropzone.js in Laravel 11.

  1. Install Dropzone.js: Start by installing Dropzone.js using npm or yarn.
npm install dropzone
  1. Include Dropzone.js in your project: You can include Dropzone.js in your project by importing it into your JavaScript file or including it directly in your HTML layout.
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/min/dropzone.min.css" rel="stylesheet">
  1. Create a Dropzone container in your HTML: Define a div element with a unique id to act as the Dropzone container.
<div id="file-dropzone" class="dropzone"></div>
  1. Initialize Dropzone in your JavaScript: Initialize Dropzone on the specified element and configure it as needed.
Dropzone.options.fileDropzone = {
  url: "/upload", // Define your upload route
  maxFilesize: 5, // Set maximum file size allowed
  acceptedFiles: '.png,.jpg,.jpeg,.gif', // Specify allowed file types
  success: function(file, response) {
    // Handle successful upload
  },
  error: function(file, response) {
    // Handle upload error
  }
};
  1. Handle file upload in your Laravel controller: Define a route and corresponding controller method to handle file uploads.
use Illuminate\Http\Request;

public function upload(Request $request) {
    $file = $request->file('file');
    // Process the uploaded file
    return response()->json(['success' => true]);
}
  1. Configure CSRF protection: Ensure that your form or AJAX requests are protected from cross-site request forgery attacks by including the CSRF token.
<meta name="csrf-token" content="{{ csrf_token() }}">

With these steps, you should have a working drag and drop file upload functionality in your Laravel application using Dropzone.js. Customize the configuration and styling according to your project requirements.

Leave a Reply