How to Add Download link in Dropzone – Laravel 8

With the use of Dropzone, you can easily add drag & drop file upload area. It displays a thumbnail after file upload but does not display a downloadable link.

In this tutorial, I show how you can add download file link in the Dropzone container after file is uploaded successfully in Laravel 8.

How to add download link in Dropzone - 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/ directory.

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).

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. Store uploaded file path to $filepath variable.

Assign 1 to $data['success'], $filepath to $data['link'] 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);

                    // File path
                    $filepath = url($location.'/'.$filename);

                    // Response
                    $data['success'] = 1;
                    $data['link'] = $filepath;
                    $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 and add download link.
  • If response.status == 0 then display error message using alert() otherwise, display download link by creating anchor tag and set href to response.link.

Completed Code

<!DOCTYPE html>
<html>
<head>
      <title>How to Add Download link in Dropzone - 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);
            }else{
                  // Download link
                  var anchorEl = document.createElement('a');
                  anchorEl.setAttribute('href',response.link);
                  anchorEl.setAttribute('target','_blank');
                  anchorEl.innerHTML = "<br>Download";
                  file.previewTemplate.appendChild(anchorEl);
             }

       });
       </script>

</body>
</html>

5. Output

View Output


6. Conclusion

I added a download link using the anchor element when the file was uploaded successfully. Returned file path with upload status from the controller.

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

Leave a Comment