Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating zip of multiple files and download in laravel

Tags:

laravel

i am using the following codes to make zip and allow user to download the zip

but its not working.it shows the error as ZipArchive::close(): Read error: Bad file descriptor.What might be the problem?i am working with laravel.

public function downloadposts(int $id)
{
    $post = Post::find($id);


    // Define Dir Folder
    $public_dir = public_path() . DIRECTORY_SEPARATOR . 'uploads/post/zip';
    $file_path = public_path() . DIRECTORY_SEPARATOR . 'uploads/post';
    // Zip File Name
    $zipFileName = $post->post_title . '.zip';
    // Create ZipArchive Obj
    $zip = new ZipArchive();
    if ($zip->open($public_dir . DIRECTORY_SEPARATOR . $zipFileName, ZipArchive::CREATE) === TRUE) {
        // Add File in ZipArchive
        foreach ($post->PostDetails as $postdetails) {
            $zip->addFile($file_path, $postdetails->file_name);
        }
        // Close ZipArchive
        $zip->close();
    }
    // Set Header
    $headers = [
        'Content-Type' => 'application/octet-stream',
    ];
    $filetopath = $public_dir . '/' . $zipFileName;
    dd($filetopath);
    // Create Download Response
    if (file_exists($filetopath)) {
        return response()->download($filetopath, $zipFileName, $headers);
    }

    return redirect()->back();
}

like image 784
Udipta Gogoi Avatar asked Dec 07 '22 14:12

Udipta Gogoi


1 Answers

For Laravel 7.29.3 PHP 7.4.11

Create a GET route in api.php

Route::get('/downloadZip','ZipController@download')->name('download');

Create controller ZipController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use File;

class ZipController extends Controller
{
    public function download(Request $request)
    {
        $zip = new \ZipArchive();
        $fileName = 'zipFile.zip';
        if ($zip->open(public_path($fileName), \ZipArchive::CREATE)== TRUE)
        {
            $files = File::files(public_path('myFiles'));
            foreach ($files as $key => $value){
                $relativeName = basename($value);
                $zip->addFile($value, $relativeName);
            }
            $zip->close();
        }

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

In the public folder make sure you have a folder myFiles. This snippet will get every file within the folder, create a new zip file and put within the public folder, then when route is called it returns the zip file created.

like image 84
Hugo Ramirez Avatar answered Feb 12 '23 14:02

Hugo Ramirez