I have developed a digital asset manager using Laravel 10. When the user downloads more that one asset i create a zip file and use laravel’s response()->download()
function to download it. Here is the function.
`
public function downloadAssets(Request $request){
$assetIds = $request->input(‘assetIds’);
// Create a temporary zip file
$zipFileName = time().'_assets'.'.zip';
$zipFilePath = storage_path('app/public/images/archive/original/' . $zipFileName);
$zip = new ZipArchive;
$zip->open($zipFilePath, ZipArchive::CREATE);
foreach($assetIds as $assetId){
$asset = Asset::find($assetId);
if(str_starts_with($asset->type, 'image/svg')){
$filePath = storage_path('app/public/images/archive/svg/'.$asset->filename);
}
elseif(str_starts_with($asset->type, 'video')){
$filePath = storage_path('app/public/videos/original/'.$asset->filename);
}
else{
$filePath = storage_path('app/public/images/archive/original/'.$asset->filename);
}
$zip->addFile($filePath, $asset->filename);
}
$zip->close();
$headers = [
'Content-Type' => 'application/zip',
];
$response = response()->download($zipFilePath, $zipFileName, $headers);
return $response;
}
`
The problem is that if i open the file i get the error in windows “The archive is either in unknown format or damaged”.
I tried downloading the file with ftp and had no problems. I also had not problems downloading the file from the browser by hitting the url or the file.
I tried adding 'Content-Disposition' => 'attachment; filename="' . $zipFileName . '"',
in the headers and it didn’t work. I also trying adding ob_clean() and it didn’t work.