Drag and drop image file upload using Dropzone in laravel

By Ved Prakash N | Apr 05, 2023 | Laravel
Share : Whatsapp

https://www.fundaofwebit.com/post/drag-and-drop-image-file-upload-in-laravel

Drag & Drop File Uploading in Laravel 10 / 9 / 8 / 7 / 6 using Dropzone JS


In this post, we will be learning how to drag and drop file upload using dropzone js in Laravel. 

you will learn Laravel 8/9/10 dropzone file upload.

Lets take an example of Gallery images where we will drag and drop the images for upload in Laravel using dropzone jQuery plugin.  

So, let's get started To implement drag and drop file uploading using Dropzone JS in Laravel, you can follow these steps:


Step 1: Dropzone JS : You can include Dropzone Css & JS CDN link in your project.

Dropzone V7 cdn link:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>

Dropzone V5 cdn link

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.0/min/dropzone.min.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.0/dropzone.js"></script>


Add Bootstrap CDN links to design the FORM more user friendly.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/js/bootstrap.bundle.min.js"></script>


Step 2: Create a new Laravel Blade view for your file upload form in the following path: resources/views/gallery/upload.blade.php

open upload.blade.php and paste the below code:

@extends('layouts.app')

@section('content')

<div class="container mt-4">
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <div class="card-header">
                    <h4 class="mb-0">Drop Multiple Images</h4>
                </div>
                <div class="card-body">

                    <label>Drag and Drop Multiple Images (JPG, JPEG, PNG, .webp)</label>

                    <form action="{{ url('gallery/upload') }}" method="POST" enctype="multipart/form-data"
                        class="dropzone" id="myDragAndDropUploader">
                        @csrf
                    </form>

                    <h5 id="message"></h5>

                </div>
            </div>
        </div>
    </div>
</div>

@endsection

In this example, the form has an ID of "dropzone" and the action attribute is set to the route where you want to handle the file upload.

Step 3: Initialize Dropzone JS in your JavaScript file or in your main blade file:

<script type="text/javascript">

var maxFilesizeVal = 12;
    var maxFilesVal = 2;

    // Note that the name "myDragAndDropUploader" is the camelized id of the form.
    Dropzone.options.myDragAndDropUploader = {

        paramName:"file",
        maxFilesize: maxFilesizeVal, // MB
        maxFiles: maxFilesVal,
        resizeQuality: 1.0,
        acceptedFiles: ".jpeg,.jpg,.png,.webp",
        addRemoveLinks: false,
        timeout: 60000,
        dictDefaultMessage: "Drop your files here or click to upload",
        dictFallbackMessage: "Your browser doesn't support drag and drop file uploads.",
        dictFileTooBig: "File is too big. Max filesize: "+maxFilesizeVal+"MB.",
        dictInvalidFileType: "Invalid file type. Only JPG, JPEG, PNG and GIF files are allowed.",
        dictMaxFilesExceeded: "You can only upload up to "+maxFilesVal+" files.",
        maxfilesexceeded: function(file) {
            this.removeFile(file);
            // this.removeAllFiles();
        },
        sending: function (file, xhr, formData) {
            $('#message').text('Image Uploading...');
        },
        success: function (file, response) {
            $('#message').text(response.success);
            console.log(response.success);
            console.log(response);
        },
        error: function (file, response) {
            $('#message').text('Something Went Wrong! '+response);
            console.log(response);
            return false;
        }
    };
</script>

This code initializes Dropzone JS with some options such as max filesize, accepted file types, and the text to display for the default message. The init function sets up event listeners for success and error messages when files are uploaded.

Step 4: Create a route in your Laravel application that handles the file upload in the following path: routes/web.php 

Route::post('gallery/upload', [App\Http\Controllers\GalleryController::class, 'upload']);


Step 5: Create a method in your Laravel controller that handles the file upload. Eg: in the following path: app/Http/Controller/GalleryController.php

lets open GallleryController.php and paste the below function or method :

public function upload(Request $request)
{
    if($request->hasFile('file')){

        $uploadPath = "uploads/gallery/";

        $file = $request->file('file');

        $extention = $file->getClientOriginalExtension();
        $filename = time().'-'.rand(0,99).'.'.$extention;
        $file->move($uploadPath, $filename);

        $finalImageName = $uploadPath.$filename;

        Gallery::create([
            'image' => $finalImageName
        ]);

        return response()->json(['success' => 'Image Uploaded Successfully']);
    }
    else
    {
        return response()->json(['error' => 'File upload failed.']);
    }
}

This code checks if the uploaded file is valid, moves the file to the "uploads/gallery" directory and returns a JSON response with a success or error message.

In this above laravel controller method, we are also saving the data of images uploaded as Gallery. So, lets create the Model & Migration.

Step 6: Create a migration as follows:

lets run this laravel artisan command to create migration file for gallery

php artisan make:migration create_galleries_table

once, successfully created, lets add the column names as given below in following path: database/migration/create_galleries_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGalleriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('galleries', function (Blueprint $table) {
            $table->id();
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('galleries');
    }
}


Step 4: Create a model named Gallery as follows:

lets run this laravel artisan command to create Model file for gallery

php artisan make:model Gallery
once, successfully created, lets update the fields as given:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Gallery extends Model
{
    use HasFactory;

    protected $table = 'galleries';

    protected $fillable = [
        'image'
    ];
}

That's it! You should now have a user-friendly drag and drop file upload form in your Laravel application using Dropzone JS.