如何下载Zip文件到浏览器

时间:2018-01-29 08:08:01

标签: php laravel-4 zip

我正在尝试将一些图像作为zip文件下载到我的pc下载文件夹中。但它总是下载到项目公用文件夹。可能是什么问题?

这是我的代码

$photos = json_decode(Input::get('photos'));
$dir = time();
foreach($photos as $file){
    $imgName = last(explode('/', $file));
    $path = public_path('downloads/'.$dir);


    if(!File::exists($path)){
        File::makeDirectory($path, 0775, true);
    }

    ImageHandler::downloadFile($file, $path.'/'.$imgName);

}

$rootPath = realpath($path);

$zip = new ZipArchive();
$file_name = 'photos.zip';
$zip->open( $file_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);

/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file1)
{
    // Skip directories (they would be added automatically)
    if (!$file1->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file1->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath));

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);

    }
}

$zip->close();


header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");

readfile($filePath);
exit;

0 个答案:

没有答案