Geek Culture
Published in

Geek Culture

Drag and Drop Upload Image/File Using Laravel

Hello, how are you all friends, I hope you are always healthy and successful. Back again with Temanngoding.com, this time we will discuss Laravel again.

This time we will discuss a tutorial on how to upload files or images using the Dropzone.js plugin. We will try to upload one or more files at the same time. and we will create an attractive appearance when uploading files. DropzoneJs is an open-source library that you can use to perform java script activities.

You can study other laravel tutorials:

REST API Login & Register With Sanctum Laravel

Upload Files using Ajax in Laravel

Laravel 8 Generate PDF Files using DomPDF

1. Create a Laravel Project

Run the composer command as follows:

composer create-project laravel/laravel --prefer-dist file-upload

And go into root :

cd file-upload

2. Create Route

Next we will create two routes, the first we will create to create the form. And the second one we use to create a file/image storage function.

enter the code below in the routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UploadController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('upload-ui', [UploadController::class, 'uploadUi' ]);
Route::post('file-upload', [UploadController::class, 'FileUpload' ])->name('FileUpload');

3. Upload Controller

To build drag and drop file upload feature we need to create controller, so fire below command from command prompt.

php artisan make:controller UploadController

app/Http/Controllers/UploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
/**
* Generate Upload View
*
* @return void
*/
public function uploadUi()
{
return view('upload-view');
}
/**
* File Upload Method
*
* @return void
*/
public function FileUpload(Request $request)
{
$image = $request->file('file');
$imageName = time().'.'.$image->extension();
$image->move(public_path('images'),$imageName);
return response()->json(['success'=>$imageName]);
}
}

4. Create Blade View

The last step, create a blade file in resources/views/dropzone-file-upload.blade.php.

<!DOCTYPE html>
<html>
<head>
<title>Laravel 8|7 Drag And Drop File/Image Upload Examle </title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.2/dropzone.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.2/min/dropzone.min.js"></script>
<script>
var dropzone = new Dropzone('#file-upload', {
previewTemplate: document.querySelector('#preview-template').innerHTML,
parallelUploads: 3,
thumbnailHeight: 150,
thumbnailWidth: 150,
maxFilesize: 5,
filesizeBase: 1500,
thumbnail: function (file, dataUrl) {
if (file.previewElement) {
file.previewElement.classList.remove("dz-file-preview");
var images = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
for (var i = 0; i < images.length; i++) {
var thumbnailElement = images[i];
thumbnailElement.alt = file.name;
thumbnailElement.src = dataUrl;
}
setTimeout(function () {
file.previewElement.classList.add("dz-image-preview");
}, 1);
}
}
});

var minSteps = 6,
maxSteps = 60,
timeBetweenSteps = 100,
bytesPerStep = 100000;
dropzone.uploadFiles = function (files) {
var self = this;
for (var i = 0; i < files.length; i++) {
var file = files[i];
totalSteps = Math.round(Math.min(maxSteps, Math.max(minSteps, file.size / bytesPerStep)));
for (var step = 0; step < totalSteps; step++) {
var duration = timeBetweenSteps * (step + 1);
setTimeout(function (file, totalSteps, step) {
return function () {
file.upload = {
progress: 100 * (step + 1) / totalSteps,
total: file.size,
bytesSent: (step + 1) * file.size / totalSteps
};
self.emit('uploadprogress', file, file.upload.progress, file.upload
.bytesSent);
if (file.upload.progress == 100) {
file.status = Dropzone.SUCCESS;
self.emit("success", file, 'success', null);
self.emit("complete", file);
self.processQueue();
}
};
}(file, totalSteps, step), duration);
}
}
}
</script>
<style>
.dropzone {
background: #e3e6ff;
border-radius: 13px;
max-width: 550px;
margin-left: auto;
margin-right: auto;
border: 2px dotted #1833FF;
margin-top: 50px;
}
</style>
</head>
<body>
<div id="dropzone">
<form action="{{ route('FileUpload') }}" class="dropzone" id="file-upload" enctype="multipart/form-data">
@csrf
<div class="dz-message">
Drag and Drop Single/Multiple Files Here<br>
</div>
</form>
</div>
</body>
</html>

The Dropzone plugin is called here using a CDN link (JavaScript and CSS).

Dropzone object initialized with file upload id; we have also implemented a small setting for the file upload function.

To style drag and drop components, we combine styles using CSS. We pass dropzoneFileUpload with route() method in action directive.

Now, you can upload single and multiple files using drag and drop, also with click events.

Run the command to start the application:

php artisan servehttp://localhost:8000/upload-ui

This will be the result when you successfully upload the image using drag and drop.

That’s the tutorial this time, that I can convey.

Thanks.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store