How to download zip file through browser in laravel?

Member

by ryleigh , in category: PHP CMS , a month ago

How to download zip file through browser in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , a month ago

@ryleigh 

To enable users to download a zip file through the browser in Laravel, you can follow these steps:

  1. Create a route in your web.php file that points to a controller method:
1
Route::get('/download-zip', 'ZipDownloadController@downloadZip');


  1. Create a controller named ZipDownloadController using the Artisan command:
1
php artisan make:controller ZipDownloadController


  1. In the ZipDownloadController, create a method called downloadZip that will generate and download the zip file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use ZipArchive;
use File;

class ZipDownloadController extends Controller
{
    public function downloadZip()
    {
        $zip = new ZipArchive;
        $fileName = 'example.zip';
        
        if ($zip->open(public_path($fileName), ZipArchive::CREATE) === TRUE) {
            // Add files to the zip file
            $zip->addFile(public_path('file1.txt'), 'file1.txt');
            $zip->addFile(public_path('file2.txt'), 'file2.txt');
            
            $zip->close();
        }

        return response()->download(public_path($fileName));
    }
}


  1. Make sure to have the files that need to be zipped in your public directory. In this example, file1.txt and file2.txt should be placed inside the public directory.
  2. Finally, create a link in your blade file that points to the URL of the route you created:
1
<a href="{{ url('/download-zip') }}">Download ZIP file</a>


When a user clicks on the "Download ZIP file" link, it will trigger the downloadZip method in the ZipDownloadController, which will generate and download the zip file containing the specified files.