Implementing Drag-and-Drop File Uploads with Dropzone.js in Laravel 11

Apr 20, 2024 | Laravel 11 Laravel


Hello Dev,

In this post, I'll guide you through implementing drag-and-drop file upload functionality using Dropzone.js in a Laravel 11 application.

Dropzone.js simplifies file uploads on the web by enabling a user-friendly drag-and-drop interface. It allows users to easily upload files by dragging them onto a specified area, complete with features like file previews and progress indicators, enhancing the overall user experience.

In this example, we'll start by creating an "images" table with columns for "name," "filesize," and "path." Then, we'll design a basic web page where users can drag and drop multiple images for upload. We'll utilize Dropzone.js for handling the drag-and-drop file upload process. The uploaded images will be saved both to the "images" folder on the server and to the database. Additionally, we'll display the uploaded images within the Dropzone interface. Let's dive into the implementation steps:

To implement drag and drop file upload using Dropzone.js in a Laravel 11 application, follow these steps:

Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel laravel-dropzone
Read Also: determining user location in laravel 11 using ip addresses Step 2: Install Dropzone.js

You can include Dropzone.js in your project by downloading it from the official website or using a CDN. For simplicity, we'll use the CDN in this example.

Step 3: Create a Migration for the Images Table

Create a migration for the images table:

php artisan make:migration create_images_table

Edit the migration file to include the necessary columns:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('filesize');
            $table->string('path');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('images');
    }
};

Run the migration:

php artisan migrate
Step 4: Create a Model for the Images Table

Create a model for the images table:

php artisan make:model Image
app/Models/Image.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Image extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'filesize', 'path'
    ];
}
Step 5: Create a Controller

Create a controller to handle the file upload:

php artisan make:controller ImageController

In app/Http/Controllers/ImageController.php, add methods to handle the file upload:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
use App\Models\Image;
 
class DropzoneController extends Controller
{
    /**
     * Generate Image upload View
     *
     * @return void
     */
    public function index(): View
    {
        $images = Image::all();
        return view('dropzone', compact('images'));
    }
      
    /**
     * Image Upload Code
     *
     * @return void
     */
    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $imageName = time().'.'.$request->file->extension();  
        $request->file->move(public_path('images'), $imageName);

        $image = new Image;
        $image->name = $imageName;
        $image->filesize = $request->file->getSize();
        $image->path = 'images/'.$imageName;
        $image->save();

        return response()->json(['success' => $imageName]);
    }
}
Step 6: Create a Route

In routes/web.php, add a route for the file upload:

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
Route::post('/upload', [ImageController::class, 'store']);
Step 7: Create the View

Create a new Blade file resources/views/upload.blade.php and include Dropzone.js:

laravel 11, dropzone.js, file upload, drag-and-drop, web development, image upload
<!DOCTYPE html>
<html>
<head>
    <title>Implementing Drag-and-Drop File Uploads with Dropzone.js in Laravel 11 -- ITErrorSolution.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.css" rel="stylesheet">
</head>
<body>
    <form action="/upload" class="dropzone" id="my-awesome-dropzone"></form>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>
    <script>
        Dropzone.options.myAwesomeDropzone = {
            paramName: "file", // The name that will be used to transfer the file
            maxFilesize: 2, // MB
            acceptedFiles: "image/*",
            init: function() {
                this.on("success", function(file, response) {
                    console.log(response);
                });
            }
        };
    </script>
</body>
</html>
Read Also: integrating google charts in laravel 11: a comprehensive guide if HTML file script not work you can Change This Script
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone-min.js"></script>
    <link href="https://unpkg.com/dropzone@6.0.0-beta.1/dist/dropzone.css" rel="stylesheet" type="text/css" />
Step 8: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/upload

This tutorial demonstrates how to implement a drag and drop file upload feature in a Laravel 11 application using Dropzone.js, including saving the uploaded images to a folder and the database, and displaying the uploaded images in the Dropzone box.

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"