AppDividend
Latest Code Tutorials

Laravel Dropzone Image Upload Tutorial With Example

Laravel Multiple Images Uploading Using Dropzone

435

Get real time updates directly on you device, subscribe now.

Laravel Dropzone Image Upload Tutorial, we will discuss today. Dropzone is the most famous, free and open source library that provides drag and drop file uploads with image previews. In this example, I will be using Laravel 5.6, but you can follow along using previous versions as well.

This tutorial explains the following:

  • Uploading multiple images with dropzone
  • Saving images with different file names to the database
  • Removing images direct from dropzone preview box

Laravel Dropzone Image Upload Tutorial With Example

We are going to Configure Laravel Project.

Step 1: Download Laravel Project

Establish  Laravel Project by the typing following command.

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

Step 2: Setup a MySQL database

Setup 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 put this following code in itIn this file, we will be adding 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 are creating a form and attaching dropzone class to it. Further, we have some text that will be displayed in our upload box. Also, if that image is uploaded successfully, it will show a tick unless it will display cross and error.

Step 5: Configure Dropzone

Now we write all the configurations for Dropzone. So add 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.

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

Step 6: Create one controller and route 

php artisan make:controller ImageUploadController

It will create one controller file called ImageUploadController.php

we register route in routes  >>  web.php file. So let us do it.

Related Posts
1 of 36
//web.php

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

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

// ImageUploadController.php

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

In create method, we are simply returning imageupload which we have created.

laravel dropzone file upload example

 

Step 7: Save File into Database

We need coding 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]);
    }

Laravel Multiple Images Uploading with drag and drop using dropzone.js example

Step 8: Remove File From Database

Now, we add removedFile() function in 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 fileDestroy() function to delete file from database. Add 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;  
    }
}

Finally, Our Laravel Dropzone Image Upload Tutorial With Example is over. Thanks for taking.

 

1 Comment
  1. rajiv bikram says

    very helpful post thank you for sharing. keep it great work man.

Leave A Reply

Your email address will not be published.

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