创建Zip和强制下载
我正在使用Laravel 4.2,并且希望设置一个区域,在该区域中生成一个zip文件供用户下载。
我不断收到错误
文件“myzip.zip不存在”
我目前的代码是:
// Here we choose the folder which will be used.
$dirName = public_path() . '/uploads/packs/'.$pack_id;
// Choose a name for the archive.
$zipFileName = 'myzip.zip';
// Create "MyCoolName.zip" file in public directory of project.
$zip = new ZipArchive;
if ( $zip->open( public_path() . '/' . $zipFileName, ZipArchive::CREATE ) === true )
{
// Copy all the files from the folder and place them in the archive.
foreach ( glob( $dirName . '/*' ) as $fileName )
{
$file = basename( $fileName );
$zip->addFile( $fileName, $file );
}
$zip->close();
$headers = array(
'Content-Type' => 'application/octet-stream',
);
// Download .zip file.
return Response::download( public_path() . '/' . $zipFileName, $zipFileName, $headers );
任何人都可以帮助我,至于为什么我得到不存在的错误?
谢谢!
从Laravel文档:http://laravel.com/docs/4.2/responses#special-responses
创建文件下载响应
return Response::download($pathToFile); return Response::download($pathToFile, $name, $headers);
也许你应该避免重复第二个
$zipFileName在你的最后一行代码中。
您可以按照以下方式“创建多个文件的zip文件并以PHP下载”。
要创建多个文件的zip文件并使用PHP进行下载,它具有以下一些功能:
当压缩文件准备就绪时,它将自动下载。
//get path of files
$path = base_path();
$file_path = $path."/../uploads/advatise/";
//getting data from database
$row = $this->getRow($ids);
//if data exist
if($row) {
//multiple images in single attrubute
$images=$row->advertise_image;
$images=explode(",",$images);
//creating zip object
$zip = new ZipArchive();
//creating file name
$DelFilePath="images".$row->id.".zip";
//if file exists then to delete it
if(file_exists($file_path.$DelFilePath)) {
unlink ($file_path.$DelFilePath);
}
//if not exist then to create zip file
if ($zip->open($file_path.$DelFilePath, ZIPARCHIVE::CREATE)
!= TRUE) {
die ("Could not open archive");
}
//loop on the images/file to add in zip
foreach ($images as $key => $image) {
$zip->addFile($file_path.$image,$image);
}
// close and save archive
$zip->close();
//opening zip and saving directly on client machine
header("Location:".Request::root()."/uploads/advatise/".$DelFilePath);
}
exit;