Image upload using dropzone in Laravel

For any project, Image uploading is a common requirement in web development projects, and Laravel, being a powerful PHP framework, offers a convenient solution to handle this task efficiently. With Dropzone, we can improve and implement file-related operations like allowing users to upload a specific number of files, size, or even type to upload. Using Dropzone can reduce implementation time.

Dropzone.js is a popular JavaScript library that provides an elegant drag-and-drop file upload feature with progress bars. We will walk through the process step-by-step, using simple and easy-to-understand explanations, to ensure a smooth learning experience.

In this tutorial, we will explore how to implement image uploads using the Dropzone.js library in Laravel.

Let’s assume, you already have the Laravel application up and running. IF not open the official Laravel document and create a fresh application and setup it up. Then perform a further operation on it.

Install and Configure Dropzone.js

To utilize Dropzone.js in our Laravel project, we must install the library and its dependencies. Open the command line and navigate to your project directory. Then, run the following commands:

npm install dropzone

Here, we have used npm to install Dropzone. However, you can download files and implement them into code manually or even use CDNs for the same.

Next, we need to include the necessary JavaScript and CSS files. Open the resources/js/app.js file and add the following code:

import Dropzone from 'dropzone';

Dropzone.autoDiscover = false;

Similarly, open the resources/sass/app.scss file and add the following code:

@import '~dropzone/dist/dropzone';

Create Upload Route and Controller

Now, let’s set up the route and controller to handle image uploads. Open the routes/web.php file and add the following route definition:

Route::post('/upload', 'UploadController@upload')->name('upload');

Next, create a new controller called UploadController using the command line. Open the terminal and enter the below command:

php artisan make:controller UploadController

It will create a new controller file at app/Http/Controllers/UploadController.php. Let’s modify it as per our requirements:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    public function upload(Request $request)
    {
        $image = $request->file('file');
        $imagePath = $image->store('uploads', 'public');

        return response()->json(['image_path' => '/storage/' . $imagePath]);
    }
}

Here, we have created a new method called upload. This method will handle upload logic for getting the file from request and storing it in server storage.

The above code will store files in the public/uploads directory specifically:

Create the Upload View

Before continuing, let’s create the view file that will contain the HTML markup and JavaScript code for implementing Dropzone.js.

Create a new file named upload.blade.php in the resources/views directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload</title>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <script src="{{ asset('js/app.js') }}" defer></script>
    <style>
        .dropzone {
            border: 2px dashed #0087F7;
            border-radius: 5px;
            background: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Image Upload</h1>

        <form action="{{ route('upload') }}" class="dropzone" id="my-dropzone" enctype="multipart/form-data">
            @csrf
        </form>
    </div>

    <script>
        Dropzone.options.myDropzone = {
            paramName: "file",
            maxFilesize: 2, // Maximum file size in megabytes
            acceptedFiles: ".jpg,.jpeg,.png,.gif",
            init: function () {
                this.on("success", function (file, response) {
                    console.log(response);
                });
            }
        };
    </script>
</body>
</html>

In the blade file, we have included CSS and JS for our application and created a simple form. In the script part, we have initialized Dropzone with some configurations like a name to be sent while submitting, maximum file size, and allowed file types. You can check all other configuration options at Dropzone Configuration options.

Render the Upload View

One more thing, we need to do is render a view to the user whenever a user visits a specific URL. Let’s create a new route for rendering the upload form to a user. Here, we will just simply return to the callback method of the route. It’s not idle to use the callback function directly.

Open the routes/web.php file and add the following route definition:

Route::get('/upload', function () {
    return view('upload');
});

Test the Image Upload

Finally, start the Laravel development server using the command:

php artisan serve

Open your web browser and navigate to http://localhost:8000/upload. You should see the image upload form powered by Dropzone.js. Try dragging and dropping an image file onto the form, and you should see the upload progress and success message in the browser console.

Conclusion

Here, we have taken a simple but practical example of implementing image uploading using Dropzone.js in Laravel. You can further enhance your logic by implementing it as per your requirement and using an additional set of configuration options.