Dropzone is the most famous, free, open-source library that provides drag and drop file uploads with image previews. In this example, I will be using Laravel, but you can follow along using previous versions.
Laravel Dropzone Image Upload
- First, upload multiple images with dropzone.
- Saving images with different file names to the database.
- Removing images direct from the dropzone preview box.
Step 1: Download 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
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.
- ImageUpload.php model.
- 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 the following code in it. In 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 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 will display cross and error.
Step 5: Configure Dropzone
Now 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.
- 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.
- renameFile function invoked before the file is uploaded to the server and renames the file.
-
acceptedFiles checks the file’s mime type or extension against this list. We define .jpeg,.jpg,.png,.gif. You can change based on your needs.
- addRemoveLinks is set to true. Dropzone will display the 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 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 are merely returning the imageupload which we have created.
Step 7: Save File into 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]); }
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 is over. Thanks for taking it.
very helpful post thank you for sharing. keep it great work man.
Great post.
A question, when the fileStore() function is called?
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.
me also same prob?did u fix it
when i uploaded file into drop box console log show me this error
“POST http://127.0.0.1:8000/admin/store 500 (Internal Server Error)”
would you please help me ?
ThnkYou
copied exactyle but does not work:
exception: “Symfony\Component\HttpKernel\Exception\HttpException”
Perfect Code, thanks
php artisan migration
https://stackoverflow.com/questions/42244541/laravel-migration-error-syntax-error-or-access-violation-1071-specified-key-wa
source code : https://github.com/thusithawijethunga/laravel-with-dropzone
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.
Also you should used named routes whenever possible. This tutorial is a little amateur.
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’)
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
it very helpful,Thank you .
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 🙂
me too bro, it should be checked again 🙁
Very nice and helpful