Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
php
communitycreator

How to use Zipper to create and download zip files in Laravel

Chinweuba Elijah Azubuike

What is Chumper/Zipper?

Zipper is a package that can be incorporated into Laravel to enable the application to work with zipping files and folders.

When a user wants to download a file, some applications need a file or a folder to zip and download in real-time.

How to set up Zipper

Step 1

Run the following to install Zipper:

composer require chumper/zipper

Step 2

Register Zipper in your application. In App.php, which is located in your Config directory, add the code snippets below:

In Providers:
 'providers' => [
                 'Chumper\Zipper\ZipperServiceProvider'
  ],

In aliases:
 'aliases' => [
                'Zipper' => 'Chumper\Zipper\Zipper'
             ],

Step 3

Add the following code to your web.php file, which is located in your route directory:

Route::get('download','ZipController@download');

Step 4

For testing, we create a test controller called ZipController with the command below:

php artisan make: controller ZipController

Your new controller can be found in app\Http\Controllers as ZipController.php.

How to zip a single file

In this controller, we add the download() function:

public function download()
    {
        $files = glob(public_path('folder/file.txt'));// get file path file.txt
        \Zipper::make(public_path("test.zip"))->add($files)->close();// zip the file
        return response()->download(public_path("test.zip"));// download it as the response
    }

In the code above, we pass the storage location as the argument to the glob() PHP function to get file.txt. Then, we call the make() method and we make test.zip, after which we add $files into test.zip. Finally, we return a response that enables the browser to download the test.zip file.

How to zip all files in a directory

public function download()
    {
        $files = glob(public_path('folder/*'));// get all file in the folder directory
        \Zipper::make(public_path("test.zip"))->add($files)->close();// zip the file
        return response()->download(public_path("test.zip"));// download it as the response
    }

The difference between adding a single file to a zip and adding all the files is as follows:

$files = glob(public_path('folder/*'));

Observe the * operator, which selects all the files in that directory.

RELATED TAGS

laravel
php
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring