saileshbro's avatar

Zip files and download the zip.

Hello

Actually I was trying to zip the files uploaded. I have the array of the path of files fetched from DB. I tried to implement from the articles but it gives an error while sending the response. It says zip file not found. I manually tried to create the zip file, but it after controller calls, the manually created file deletes automatically. Please give your suggestions on this. i tried this

public function show(Project $project, $type)
    {
        try {
            $files = $project[$this->types[$type]]->pluck('file')->map(static function (File $file) {
                return $file->getOriginal('url');
            });
            if ($files->isEmpty()) {
                throw new \Exception();
            }

            $zip_file = $this->types[$type] . '.zip';

            $zip = new ZipArchive;
            if ($zip->open(public_path($zip_file), ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                foreach ($files as $value) {
                    $zip->addFile($value, public_path($value));
                }
                $zip->close();
            }
            return response()->download(public_path($zip_file));

        } catch (\Exception $e) {
            throw new NotFoundHttpException();
        }
    }
0 likes
7 replies
saileshbro's avatar

@carsongrey in my project, a Model has different files, like docx file, csv an other documents. I want to get and download all the documents zipped. We can unzip it after the compressed file is downloaded.

trungtranqn91's avatar

@saileshbro My code is working well:

class CompressFileTask
{
    /**
     * Compress file and return file name.
     *
     * @param string $path      Path
     * @param string $file      file name
     * @param string $extension extension
     *
     * @return string
     */
    public function handle(string $path, string $file, string $extension)
    {
        $zip = new \ZipArchive();
        $fileName = pathinfo($file, PATHINFO_FILENAME);
        $zip->open($path.$fileName.$extension, \ZipArchive::CREATE);
        $zip->addFile($path.$file, $file);
        $zip->close();

        return $fileName.$extension;
    }
}


 

Call it

 app(CompressFileTask::class)->handle($path, $fileName, '.gz');
saileshbro's avatar

@trungtranqn91 actually it was the issue with the server temp folder. I had to change the php.ini file, and it worked.

Please or to participate in this conversation.