Implementation method of creating Zip compressed file and providing download in Laravel

  • 2021-12-05 05:44:31
  • OfStack

If you need your users to support multi-file downloads, the best way is to create a zip package and provide downloads. Let's take a look at the implementation in Laravel through this article.

In fact, this is not about Laravel, but more about PHP. We are going to use the ZipArchive class that has existed since PHP 5.2. If we want to use it, we need to make sure that the ext-zip extension in php. ini is turned on.

Task 1: Save the user's invoice file to storage/invoices/aaa001.pdf

Here's a code demonstration:


$zip_file = 'invoices.zip'; //  The name of the compressed package to download 
//  Initialization  PHP  Class 
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
$invoice_file = 'invoices/aaa001.pdf';
//  Add a file: Section 2 Parameters are the path of the file to be compressed in the compressed package 
//  So, it will be in  ZIP  Create another 1 A person named  "storage/"  And put the files in the directory. 
$zip->addFile(storage_path($invoice_file), $invoice_file);
$zip->close();
//  We will return the file as it is as soon as it is downloaded 
return response()->download($zip_file);

The example is simple, isn't it?

*

Task 2: Compress all files into the storage/invoices directory

No changes need to be made to the Laravel aspect, we just need to add a bit of simple PHP code to iterate through these files.


$zip_file = 'invoices.zip';
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$path = storage_path('invoices');
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file)
{
 //  We want to skip all subdirectories 
 if (!$file->isDir()) {
  $filePath  = $file->getRealPath();

  //  Use  substr/strlen  Get the file extension 
  $relativePath = 'invoices/' . substr($filePath, strlen($path) + 1);

  $zip->addFile($filePath, $relativePath);
 }
}
$zip->close();
return response()->download($zip_file);

It's basically finished here. You see, you don't need any Laravel extension pack to implement this compression method.

PS: Let's take a look at laravel from getting started to mastering file processing compression/decompression zip

1: Add this package to the list of required packages composer. json

"chumper/zipper": "1.0.x"

2: Command line execution

composer update

3: Configure app/config/app. php


add to providers Chumper\Zipper\ZipperServiceProvider::class
add to aliases 'Zipper' => Chumper\Zipper\Zipper::class

4: Traverse the file and package it into a compressed package


$files = Array();
    foreach ($student as $key => $data) {
      if ($data->photopath != null) {
        $check = glob(storage_path('photo/' . $data->photopath));
        $files = array_merge($files, $check);
      }
    }
 Zipper::make(storage_path() . '/systemImg/' . $name)->add($files)->close();

5: Read the compressed package file


  Zipper::make( storage_path() . '/photo/photos')->extractTo(storage_path('temp'));
 $zip = new \ZipArchive();// Method 2 Stream processing, new 1 A ZipArchive Object of 
        $logFiles = Zipper::make($path)->listFiles('/\.png$/i');
        if ($zip->open($path) === TRUE) {
          foreach ($logFiles as $key) {
            $stream = $zip->getStream($key);
            $str = stream_get_contents($stream); // Notice here the encoding of the obtained text 
            $name = iconv("utf-8", "gb2312//IGNORE", $key);
            file_put_contents(storage_path() . '\temp\\' . $name, $str);
          }
        } else {
          return '{"statusCode":"300", "message":" Upload failed, please check photos "}';
        }

Summarize


Related articles: