Drag and Drop file upload with Dropzone in Laravel 8

Dropzone is a Javascript plugin that provides drag and drop file uploads with image previews. It is not dependent on external JavaScript libraries like – jQuery.

It is easy to add on the page.

In this tutorial, I show how you can upload file using Dropzone in Laravel 8.

Drag and Drop file upload with Dropzone in Laravel 8


Contents

  1. Download
  2. Controller
  3. Route
  4. View
  5. Output
  6. Conclusion

1. Download

  • Download Dropzone library from here
  • Extract the downloaded file in public/ folder.

2. Controller

  • Create PageController Controller.
php artisan make:controller PageController
  • Open app/Http/Controllers/PageController.php file.
  • Create two methods –
    • index – Load index view.
    • uploadFile – This method is used to upload the selected file of Dropzone.

Define file validation. I set the max file size to 2 MB (2048 Kb).

NOTE – File validation is same as defined while initializing Dropzone.

If the file is not validated then assign 0 to $data['success'] and validation response to $data['error'].

If file is validated successfully then upload the file to "files" location. Assign 1 to $data['success'] and assign Uploaded Successfully! to $data['message'].

Return $data Array in JSON format.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PageController extends Controller {

     public function index(){
          return view('index');
     }

     public function uploadFile(Request $request){

          $data = array();

          $validator = Validator::make($request->all(), [
               'file' => 'required|mimes:png,jpg,jpeg,pdf|max:2048'
          ]);

          if ($validator->fails()) {
 
              $data['success'] = 0;
              $data['error'] = $validator->errors()->first('file');// Error response

          }else{
               if($request->file('file')) {

                   $file = $request->file('file');
                   $filename = time().'_'.$file->getClientOriginalName();

                    // File upload location
                    $location = 'files';

                    // Upload file
                    $file->move($location,$filename);

                    // Response
                    $data['success'] = 1;
                    $data['message'] = 'Uploaded Successfully!';

               }else{
                     // Response
                     $data['success'] = 0;
                     $data['message'] = 'File not uploaded.'; 
               }
          }

           return response()->json($data);
     }
}

3. Route

  • Open routes/web.php file.
  • Define 2 routes –
use App\Http\Controllers\PageController;

Route::get('/', [PageController::class, 'index']);
Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');
  • The 2nd route is used for Dropzone file upload.

4. View

Create index.blade.php file in resources/views/ folder.

Store CSRF token in <meta > tag and include Dropzone library.

Dropzone Container 

  • Create a <form action="{{route('uploadFile')}}" class='dropzone' >.

Script

  • Read CSRF token from <meta > tag and assign to CSRF_TOKEN variable.
  • Disable dropzone autoDiscover – Dropzone.autoDiscover = false and initialize Dropzone in <form >.
  • Set max upload filesize to 2 MB and valid file extensions – “.jpeg,.jpg,.png,.pdf”.
  • Send CSRF token using sending event – formData.append("_token", CSRF_TOKEN);.
  • Using success event check return response.
  • If response.status == 0 means file is not uploaded. Display error message using alert().

Completed Code

<!DOCTYPE html>
<html>
<head>
      <title>Drag and Drop file upload with Dropzone in Laravel 8</title>

      <!-- Meta -->
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta charset="utf-8">
      <meta name="csrf-token" content="{{ csrf_token() }}">

      <!-- CSS -->
     <link rel="stylesheet" type="text/css" href="{{asset('dropzone/dist/min/dropzone.min.css')}}">

      <!-- JS -->
      <script src="{{asset('dropzone/dist/min/dropzone.min.js')}}" type="text/javascript"></script>

</head>
<body>

       <div class='content'>
              <!-- Dropzone -->
             <form action="{{route('uploadFile')}}" class='dropzone' ></form> 
       </div>

       <!-- Script -->
       <script>
       var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').getAttribute("content");

       Dropzone.autoDiscover = false;
       var myDropzone = new Dropzone(".dropzone",{ 
            maxFilesize: 2, // 2 mb
            acceptedFiles: ".jpeg,.jpg,.png,.pdf",
       });
       myDropzone.on("sending", function(file, xhr, formData) {
            formData.append("_token", CSRF_TOKEN);
       }); 
       myDropzone.on("success", function(file, response) {

            if(response.success == 0){ // Error
                  alert(response.error);
            }

       });
       </script>

</body>
</html>

5. Output

View Output


6. Conclusion

You can use it as a replacement for the HTML file element or for allowing drag-drop file upload.

Dropzone container only displays the image preview.

You can view this tutorial for changing the thumbnail of the non-image file.

If you found this tutorial helpful then don't forget to share.

Leave a Comment