Laravel 6.2 Dropzone Multiple Image Upload Tutorial

We know that Dropzone.js is a lightweight JavaScript library that turns an HTML element into a dropzone. This means that a user can drag and drop a file onto it, and the file gets uploaded to the server via AJAX.

In this guide, I’m going to create a simple project to upload images with DropzoneJS in Laravel 6.2. Here’s the preview of our project:

Let’s follow these steps:

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Create Model, Migration & Controller
  3. Register Routes
  4. Create Blade File

Step 1 : Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations

Step 2 : Create Model, Migration & Controller

In this step, we are going to create the book model, migration and controller. Let’s create these at once:

php artisan make:model ImageUpload -mcr

After creating the files, open the migration file from database/migrations and update the up() function like this:

timestamp_create_image_uploads_table.php
public function up()
{
    Schema::create('image_uploads', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('filename');
        $table->timestamps();
    });
}

We’ve to migrate the migration:

php artisan migrate

After that open Book model and add a $fillable array:

app/ImageUpload.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ImageUpload extends Model
{
    protected $fillable = [
        'filename'
    ];
}

Lastly, open ImageUploadController from app\Http\Controllers and paste this code:

ImageUploadController.php
<?php

namespace App\Http\Controllers;

use App\ImageUpload;
use Illuminate\Http\Request;

class ImageUploadController extends Controller
{
    public function upload()
    {
        return view('image_upload');
    }

    public function store(Request $request)
    {
        $image = $request->file('file');
        $imageName = $image->getClientOriginalName();
        $image->move(public_path('images'), $imageName);

        $imageUpload = new ImageUpload();
        $imageUpload->filename = $imageName;
        $imageUpload->save();
        return response()->json(['success' => $imageName]);
    }

    public function delete(Request $request)
    {
        $filename = $request->get('filename');
        ImageUpload::where('filename', $filename)->delete();
        $path = public_path() . '/images/' . $filename;
        if (file_exists($path)) {
            unlink($path);
        }
        return $filename;
    }
}

Step 3 : Register Routes

Let’s create the routes:

routes/web.php
Route::get('upload', 'ImageUploadController@upload');
Route::post('upload/store', 'ImageUploadController@store');
Route::post('delete', 'ImageUploadController@delete');

Step 4 : Create Blade File

Go to resources/views folder and make a blade file named ‘image_upload.blade.php’ for image upload.

image_upload.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 6.2 Dropzone Multiple Image Upload Tutorial</title>
    <meta name="_token" content="{{csrf_token()}}"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
</head>
<body>
<div class="container">

    <div class="text-center" style="margin: 20px 0px 20px 0px;">
        <a href="https://shouts.dev/" target="_blank"><img src="https://i.imgur.com/hHZjfUq.png"></a><br>
        <span class="text-secondary">Laravel 6.2 Dropzone Multiple Image Upload Tutorial</span>
    </div>

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

<script type="text/javascript">
    Dropzone.options.dropzone =
        {
            maxFilesize: 12,
            renameFile: function (file) {
                var dt = new Date();
                var time = dt.getTime();
                return time + file.name;
            },
            acceptedFiles: ".jpeg,.jpg,.png,.gif",
            addRemoveLinks: true,
            timeout: 50000,
            removedfile: function (file) {
                var name = file.upload.filename;
                $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                    },
                    type: 'POST',
                    url: '{{ url("delete") }}',
                    data: {filename: name},
                    success: function (data) {
                        console.log("File has been successfully removed!!");
                    },
                    error: function (e) {
                        console.log(e);
                    }
                });
                var fileRef;
                return (fileRef = file.previewElement) != null ?
                    fileRef.parentNode.removeChild(file.previewElement) : void 0;
            },

            success: function (file, response) {
                console.log(response);
            },
            error: function (file, response) {
                return false;
            }
        };
</script>

</body>
</html>

Our application is ready to run. Let’s run our project:

php artisan serve

Now go to the URL and test the uploader:

http://localhost:8000/upload

The tutorial is over. You can download this project from GitHub. Thank you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.