Drag and drop file upload in Laravel 6 can be possible by Dropzone js. Dropzone js is an open-source library that provides us a feature for uploading files by drag and drop. By using Dropzone js, you can upload single or multiple files in Laravel 6. Basically, the Dropzone js works with Ajax. That means the selected images or files will be uploaded asynchronously. It will not be going to reload the webpage. In the Laravel 6 series, I have already shown you to upload single and multiple images. But, in those posts, there was no option to select files or images by drag and drop. Today, through this post you will be learning how to implement drag and drop file upload in Laravel 6. So let’s continue this post.
Prerequisites
I am assuming your system is ready with the below configuration.
- PHP version >=7.3.9
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
Create New Project For Drag and Drop File Upload
I am going to start with a fresh project. If you haven’t any project then create a new project in Laravel 6.
composer create-project --prefer-dist laravel/laravel dropzone-image-upload
Now, you will have to wait until the installation finished.
In this project, after image upload, I will be inserting the image name into the database table. So, in the next step, just create a database in MySQL.
How to Resize Image in Laravel 6 Before Upload
Create and Configure Database
Open the MySQL and let’s create a database there.
CREATE DATABASE dropzone_upload;
Now, synchronize the database with the Laravel 6 drag and drop file upload project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dropzone_image_upload
DB_USERNAME=root
DB_PASSWORD=root
Create a Model and Migration For Dropzone js Upload
For inserting the image name into the database table, I will create a model and the migration. The migration file will generate the table schema. So, let’s create it.
php artisan make:model ImageUpload --migration
By hitting the above command in the terminal, it will create a model and the migration file. This migration file will be associated with the Model (ImageUpload).
Now, let’s make little change in the migration file of create_image_uploads_table.php.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImageUploadsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('image_uploads', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('image_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('image_uploads');
}
}
Once the migration is ready with the schema, we’ll require to migrate it.
How to Implement Google Autocomplete Address in Laravel 6
Migrate Table
For migrating the table schema in the database, we’ll require hitting a command in the terminal.
php artisan migrate
Create Controller
For implementing multiple file uploads using drag and drop features, we’ll have to write some code in the controller. So, for this, I will create a controller.
php artisan make:controller DropzoneFileUploadController
Hit the above command. It will create a controller. Now, paste the below functions there.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\ImageUpload;
class DropzoneFileUploadController extends Controller
{
public function index() {
return view('image-upload');
}
// ------------------------ [ Upload Image ] --------------------------
public function uploadImages(Request $request) {
$image = $request->file('file');
$imageName = $image->getClientOriginalName().'.'.$image->extension();
$image->move(public_path('images'),$imageName);
$data = ImageUpload::create(['image_name' => $imageName]);
return response()->json(["status" => "success", "data" => $data]);
}
// --------------------- [ Delete image ] -----------------------------
public function deleteImage(Request $request) {
$image = $request->file('filename');
$filename = $request->get('filename').'.jpeg';
ImageUpload::where('image_name', $filename)->delete();
$path = public_path().'/images/'.$filename;
if (file_exists($path)) {
unlink($path);
}
return $filename;
}
}
- In the index() function, I have returned a view that I am going to create in the next step.
- The uploadImage() function has created for uploading the images or files which will be dropped in the view. Also, the file name will be stored in the database table.
- Now, in the next function, I have created the functionality to delete the image.
Hence as per these functions, I will have to create a route. The route will define which function will be called. So, let’s create the routes.
Add Routes For Dropzone js
Open the routes/web.php file and then add these below routes there.
Route::get('/', 'DropzoneFileUploadController@index');
Route::post('store', 'DropzoneFileUploadController@uploadImages');
Route::post('delete', 'DropzoneFileUploadController@deleteImage');
After adding the routes, let’s create a view and configure the dropzone js. So, that we can upload images or files as per our requirements.
Create a View For Drag and Drop File Upload
For creating any view in the Laravel, we will have to navigate to the resources/views folder. According to this project, we will need a single view in which we’ll implement the dropzone js. Therefore, create a view with the name image-upload.blade.php.
Now, paste the below code there.
<!doctype html>
<html lang="en">
<head>
<title>Laravel Multiple Images Upload Using Dropzone</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="_token" content="{{csrf_token()}}" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h4 class="text-center font-weight-bold">Laravel 6 Multiple Images Upload Using Dropzone</h4>
<form method="post" action="{{url('store')}}" enctype="multipart/form-data"
class="dropzone" id="dropzone">
@csrf
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
</body>
</html>
- In the above snippet, I have created a form using Bootstrap 4.
- Also, I have added the Dropzone js library for implementing the drag and drop file upload.
- The form action has defined a route that has defined above in the route section. Therefore, when the images or files will be uploaded it will redirect to the store route.
- The store route has related to a function that is defined for moving the dropped files inside the dropzone area.
Add Dropzone js Configuration
Now, we’ll have to configure the dropzone js. So, you will have to add the below code at the end, before the closing of the body and HTML tag.
// dropzone image upload
<script type="text/javascript">
Dropzone.options.dropzone =
{
maxFilesize: 10,
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>
In the above code, I have appended some configuration of Dropzone js. You can go through the documentation of the dropzone config. You can take a look at the documentation in the detail. But, I am going to explain which I have used in the above code.
- maxFilesize – This option is used to set the number of files to be upload. So, here I have set the max file size to 10. In the Dropzone, it allows images to upload with a size of less than the 12 MB. That means you will have to resize your image before upload.
- renameFile – Dropzone provides a function to rename the file which is going to be upload. That means this function will be invoked before the file will be uploaded to the server.
- acceptedFiles – We can set the file types for the upload. Therefore, the dropzone will check the file type before upload. This can be set as per your requirement. Currently, I am uploading the images that’s why I have set the mime type as .jpeg,.jpg,.png,.gif.
- addRemoveLinks – In the Dropzone, you can remove the uploaded images or files from the uploaded list. But for achieving this feature, you will have to set it to true. It will show you an option to remove the uploaded files.
- timeout – You can set the timeout for the file upload. Currently, I have set to 5000. That’s it.
PHP File Upload Using jQuery and Ajax
Run Drag and Drop File Upload Application
Now, let’s run our application and see how is it looking?
Open the browser and hit the below URL.
localhost:8000
You will see the result as shown below.
When you will drop your images in the dropzone area, it will start uploading. After the uploading of images, you will have the option to remove the file. You can remove the files from here. It will hit an ajax call to a route named delete. And from the delete route, the deleteImage function is associated.
After uploading the image, you can see inside the project folder. The images have been uploaded successfully.
After images upload, the image’s name has been inserted into the database table. Hence, you can take a look at the database table.
Drag and Drop Multiple File Upload in PHP Using Dropzone js
Conclusion
We have learned the implementation of Dropzone js in Laravel 6. This is the easiest way to upload images or files by drag and drop. We have configured the Dropzone js functionalities in which we have enabled the remove image option. This option will be enabled once the images will be uploaded. After clicking the remove link, it will delete the uploaded image from the folder. Also, it will delete from the database table.
matthew says
I can remove image from on the view but the image is still kept inside the folder.
Umesh Rana says
You can delete the uploaded images from the folder like this –
File::delete('images/' . $image_url);