download generated zip with laravel

80 views Asked by At

I´m trying dowload zip with my files in my app laravel. To build this logic, i´m using,ZipArchive and i including all my files in foreach. Zip it´s generated ok, and files it´s included. But browser not download this file. I´m trying dowload with this code:

response()->download($zipPath, 'contratos_seleccionados.zip', $headers);
return response()->json(['success' => 'success'], 200);

My zip, it´s saved in my folder. But i need to do that user can view this file it´s download. like when we download on google.

All my logic it´s:

$path = public_path('/storage/contracts/bills/');

                if(!File::isDirectory($path)){
                    File::makeDirectory($path, 0777, true, true);
                }
                
                $fileName =  'contrato_'.$ids.'.pdf';
                $pdf->save($path . '/' . $fileName);
                $result = $pdf->download($fileName);

                $zip = new ZipArchive;
                $zipFileName = 'contratos_seleccionados.zip';
                $zipPath = public_path('/storage/contracts/'.$zipFileName);

                if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
                    $filesToZip = [
                        $path . '/' . $fileName,
                    ];

                    foreach ($filesToZip as $file) {
                        $zip->addFile($file, basename($file));
                    }

                    $zip->close();

                    if (file_exists($zipPath)) {

                        $result = response()->download($zipPath);
                        if($result){
                            //\Storage::download($zipPath, $zipFileName);
                            //\Storage::download($zipPath, "prueba.zip");
                            //\Storage::disk('contracts')->download($zipFileName);
                            $headers = [
                                'Content-Type' => 'application/zip',
                             ];
                  
                            response()->download($zipPath, 'contratos_seleccionados.zip', $headers);
                            return response()->json(['success' => 'success'], 200);
                        }
                    }

I tryed with comment code, and any way with response()->download but never show in browser file downloading.

Thanks for readme and sorry for my bad english

1

There are 1 answers

10
Kamran Allana On

Try this:

if($result) {
  $headers = [
    'Content-Type' => 'application/zip',
  ];

  response()->download(storage_path('app/public/contracts/'.$zipFileName), 'contratos_seleccionados.zip', $headers);
  return response()->json(['success' => 'success'], 200);
}