创建Zip和强制下载 - Laravel

时间:2015-06-03 09:29:04

标签: php laravel laravel-4 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 );

任何人都可以帮助我,至于为什么我得到不存在的错误?

谢谢!

2 个答案:

答案 0 :(得分:3)

来自Laravel文档:http://laravel.com/docs/4.2/responses#special-responses

创建文件下载响应

return Response::download($pathToFile);

return Response::download($pathToFile, $name, $headers);

也许你应该避免在最后一行代码中重复第二次

$zipFileName

答案 1 :(得分:1)

您可以在下面的方式“创建多个文件的zip并在P​​HP中下载”。

要创建多个文件的zip并使用PHP下载,它具有以下一些功能:

  • 它将使用ZipArchive Library创建一个zip文件。
  • 在创建文件之前,它会检查文件是否存在。
  • 如果文件存在,则会删除该文件。
  • 如果文件不存在,则会创建
  • 一个包含多个传递的zip文件。
  • 当拉链准备就绪时,它将自动下载。

    //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;