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.
Run the following to install Zipper:
composer require chumper/zipper
Register Zipper in your application. In App.php
, which is located in your Config
directory, add the code snippets below:
'providers' => [
'Chumper\Zipper\ZipperServiceProvider'
],
'aliases' => [
'Zipper' => 'Chumper\Zipper\Zipper'
],
Add the following code to your web.php
file, which is located in your route
directory:
Route::get('download','ZipController@download');
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
.
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.
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
CONTRIBUTOR
View all Courses