Laravel Dropzone Image Upload Example [Step-by-Step Guide]

Here are the steps to use the Dropzone library to upload an image in Laravel:

Step 1: Download the Laravel Project

Create a Laravel Project by typing the following command.

composer create-project --prefer-dist laravel/laravel dropzonefileupload

Step 2: Set up a MySQL database

Set up the database in the .env file.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dropzonefileupload
DB_USERNAME=root
DB_PASSWORD=

I have set up local database credentials.

Step 3: Compose a model and migration file

Type the following command in your cmd.

$ php artisan make:model ImageUpload -m

It will create two files.

  1. ImageUpload.php model.
  2. create__image_uploads_table migration file.

We need to create Schema for the image upload table. So navigate to Laravel  >>  database  >>  migrations  >>  create__image_uploads_table.

// create_image_uploads_table

 public function up()
 {
  Schema::create('image_uploads', function (Blueprint $table) {
   $table->increments('id');
   $table->text('filename');
   $table->timestamps();
  });
 }

Step 4: Create a view file

Create a file in resources  >>  views  >>   imageupload.blade.php and put the following code in itIn this file, we will be adding a dropzone for file uploading.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</head>
<body>
<div class="container">
       
    <h3 class="jumbotron">Laravel Multiple Images Upload Using Dropzone</h3>
    <form method="post" action="{{url('image/upload/store')}}" enctype="multipart/form-data" 
                  class="dropzone" id="dropzone">
    @csrf
</form>   
</body>
</html>

In this file, we do first add our bootstrap.min.css, dropzone.min.css. Then we are adding jquery.js and dropzone.js. Next, we create a form and attach the dropzone class to it.

Further, we have some text displayed in our upload box. Also, if that image is uploaded successfully, it will show a tick unless it displays a cross and error.

Step 5: Configure Dropzone

We write all the configurations for Dropzone. So add the following code in a view file.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</head>
<body>
<div class="container">
       
    <h3 class="jumbotron">Laravel Multiple Images Upload Using Dropzone</h3>
    <form method="post" action="{{url('image/upload/store')}}" enctype="multipart/form-data" 
                  class="dropzone" id="dropzone">
    @csrf
</form>   
<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: 5000,
            success: function(file, response) 
            {
                console.log(response);
            },
            error: function(file, response)
            {
               return false;
            }
};
</script>
</body>
</html>

In the file above, we are appending configuration options for Dropzone. You can find any of the configuration options available on the Dropzone documentation.

Now let’s go through each option.

  1. maxFilesize is set to 12. Dropzone will only allow images with a size of less than 12MB. You can make it smaller or higher based on your requirements.
  2. renameFile function invoked before the file is uploaded to the server and renames the file.
  3. acceptedFiles checks the file’s mime type or extension against this listWe define .jpeg,.jpg,.png,.gif. You can change it based on your needs.
  4. addRemoveLinks is set to true. Dropzone will display the Remove button to remove our uploaded file.
  5. timeout is set to 5000

Step 6: Create one controller and route 

php artisan make:controller ImageUploadController

It will create a file called ImageUploadController.php; we register routes in the routes  >>  web.php file. So let us do it.

// web.php

Route::get('image/upload','ImageUploadController@fileCreate');
Route::post('image/upload/store','ImageUploadController@fileStore');
Route::post('image/delete','ImageUploadController@fileDestroy');

The next step would be to go to the ImageUploadController.php file and add some code to the fileCreate () function.

// ImageUploadController.php

public function fileCreate()
    {
        return view('imageupload');
    }

In the create() method, we merely return the imageupload we created.

laravel dropzone file upload form

Step 7: Save the File into the Database

We need to code the fileStore() function in series to store the filename in the database.

// ImageUploadController.php

use App\ImageUpload;

public function fileStore(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]);
    }

Uploading with drag and drop using dropzone.js

Step 8: Remove the File From the Database

We add the removedFile() function in the dropzone configuration.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Multiple Images Upload Using Dropzone</title>
    <meta name="_token" content="{{csrf_token()}}" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</head>
<body>
<div class="container">
       
    <h3 class="jumbotron">Laravel Multiple Images Upload Using Dropzone</h3>
    <form method="post" action="{{url('image/upload/store')}}" enctype="multipart/form-data" 
                  class="dropzone" id="dropzone">
    @csrf
</form>   
<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("image/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>

Add the fileDestroy() function to delete files from the database. Add the following code in FileUploadController.

//ImageUploadController.php

<?php

namespace App\Http\Controllers;

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

class ImageUploadController extends Controller
{
    public function fileCreate()
    {
        return view('imageupload');
    }
    public function fileStore(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 fileDestroy(Request $request)
    {
        $filename =  $request->get('filename');
        ImageUpload::where('filename',$filename)->delete();
        $path=public_path().'/images/'.$filename;
        if (file_exists($path)) {
            unlink($path);
        }
        return $filename;  
    }
}

That’s it.

16 thoughts on “Laravel Dropzone Image Upload Example [Step-by-Step Guide]”

  1. I want to ask a question , file store is call when form submit , but in your case submit function is missing . and
    Call to a member function getClientOriginalName() on null is generate fetal error when running the script.

    So i think , you need to recheck your code and test it again.

    Reply
  2. Hi the code is 5* but if i need to refresh or get back to see the uploaded images e can’t. Can you post some code or do a tutorial how to get the images that already are stored.

    Reply
  3. Also,
    CRSF token in the ajax call should be like this
    ‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)
    not like this
    ‘X-CSRF-TOKEN’: $(‘meta[name=”_token”]’).attr(‘content’)

    Reply
  4. Hi can you please help e to integrate dropzone?
    I am trying to integrate dropzone in foreach loop but it is not working
    Please help me if you can

    Reply
  5. Thanks for this helpful content. But i would like to ask, how can i use dropzone in form? I mean, i have a form which is creating a category for my blog and i need to add featured image …

    Thanks for your assistant 🙂

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.