Laravel 9 Drag and Drop File/image Upload with Dropzone Example

Laravel drag and drop file upload with dropzone js tutorial with example. This quick guide will help you create laravel dropzone multiple files upload feature.

Uploading image or file with dropzone in Laravel is no more going to be a difficult task. I am going to share how does Laravel dropzone file upload functionality is made from scratch.

File or image uploading is everyday work for most of us, whether uploading images on Facebook, Pinterest, Instagram or any other platform.

In this tutorial, you will learn how to upload files or images by dragging and dropping in Laravel application using Dropzone.js library from the absolute beginning.

Dropzone is a lightweight open-source Javascript library that allows you to recklessly build drag ‘n’ drop file uploads with image previews, progress status, multi-file upload, by the same token synchronous uploads.

Its easy to integrate into HTML web pages, you can use the Dropzone CDN links or even import it manually by downloading their official site.

Install Laravel Application

Create laravel application anyhow make sure you have Composer installed on your system:

composer create-project laravel/laravel --prefer-dist laravel-drag-drop-image-upload

Build New Controller

A controller holds the logic to handle the drag and drop file upload, so go ahead and generate a new controller:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class ImageController extends Controller
{

    public  function index()  
    {  
        return view('welcome');  
    }

    public  function dropZone(Request $request)  
    {  
        $file = $request->file('file');
        $fileName = time().'.'.$image->extension();
        $file->move(public_path('images'),$fileName);
        return response()->json(['success'=>$fileName]);
    }
}

Adding Routes

Import controller in routes/web.php file, then define routes to display view and enabling file upload.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/

Route::get('/', [ImageController::class, 'index' ]);
Route::post('/upload-image', [ImageController::class, 'dropZone' ])->name('drag-drop');

Drag ‘n’ Drop File Upload Blade View

Finally, you have to build the view for drag and drop image file upload view, open resources/views/welcome.blade.php file and add the given below code:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <title>Laravel 8 Drag And Drop Multi Files Upload Demo</title>

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

    <script>
        var dropzone = new Dropzone('#uploadFile', {
            previewTemplate: document.querySelector('#preview-template').innerHTML,
            parallelUploads: 3,
            thumbnailHeight: 120,
            thumbnailWidth: 120,
            maxFilesize: 6,
            filesizeBase: 1500,
            thumbnail: function (file, dataUrl) {
                if (file.previewElement) {
                    file.previewElement.classList.remove("dz-file-preview");
                    var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
                    for (var i = 0; i < images.length; i++) {
                        var thumbnailElement = images[i];
                        thumbnailElement.alt = file.name;
                        thumbnailElement.src = dataUrl;
                    }
                    setTimeout(function () {
                        file.previewElement.classList.add("dz-image-preview");
                    }, 1);
                }
            }
        });
        
        var minSteps = 6,
            maxSteps = 60,
            timeBetweenSteps = 100,
            bytesPerStep = 100000;

        dropzone.uploadFiles = function (files) {
            var self = this;

            for (var i = 0; i < files.length; i++) {

                var file = files[i];
                totalSteps = Math.round(Math.min(maxSteps, Math.max(minSteps, file.size / bytesPerStep)));

                for (var step = 0; step < totalSteps; step++) {
                    var duration = timeBetweenSteps * (step + 1);
                    setTimeout(function (file, totalSteps, step) {
                        return function () {
                            file.upload = {
                                progress: 100 * (step + 1) / totalSteps,
                                total: file.size,
                                bytesSent: (step + 1) * file.size / totalSteps
                            };

                            self.emit('uploadprogress', file, file.upload.progress, file.upload
                                .bytesSent);
                            if (file.upload.progress == 100) {
                                file.status = Dropzone.SUCCESS;
                                self.emit("success", file, 'success', null);
                                self.emit("complete", file);
                                self.processQueue();
                            }
                        };
                    }(file, totalSteps, step), duration);
                }
            }
        }

    </script>

    <style>
        .dropzone {
            max-width: 500px;
            margin-left: auto;
            margin-right: auto;
            border-radius: 14px;
            margin: 60px 0 0 0;
            background: #e3e6ff;
            border: 1px dotted #4e4e4e;            
        }

    </style>
</head>

<body>
    <div id="dropzone">
        <form action="{{ route('drag-drop') }}" class="dropzone" id="uploadFile" enctype="multipart/form-data">
            @csrf
            <div class="dz-message">
                Drag 'n' Drop Files<br>
            </div>
        </form>
    </div>
</body>

</html>

Run Application

Use command to run the application:

php artisan serve
http://127.0.0.1:8000

Conclusion

The Laravel drag and drop file upload tutorial is over, i hope this will be a beneficial tutorial for you to learn the concept of image uploading with the dropzone library in the Laravel project.