如何通过浏览器 Laravel 下载 zip 文件?

jos*_*eph 0 php zip laravel laravel-4

我正在尝试将一些图像压缩为用户选择的。到目前为止,我已经提出了一个压缩解决方案。我的问题是在我将相关数据压缩到 zip 文件后如何通过浏览器下载它。我尝试了不同的方法仍然不起作用。当我创建 zip 时,它存储在公共文件夹中。如何通过浏览器从那里下载 zip 文件?

这是我的代码

$photos = json_decode(Input::get('photos'));
$dir = time();
foreach ($photos as $file) {
   /* Log::error(ImageHandler::getUploadPath(false, $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_file = 'Photos.zip';
$public_dir = public_path();
$zip = new ZipArchive();
$zip->open($zip_file, 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) + 1);
        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
     }
}

// Zip archive will be created only after closing object
$zip->close();
$fileurl = public_path()."/Photos.zip";
if (file_exists($fileurl))
{
      return Response::download($fileurl, 'Photos.zip', ['Content-Length: '. filesize($fileurl)]);
} else {
      exit('Requested file does not exist on our server!');
}
Run Code Online (Sandbox Code Playgroud)

作为回应,我得到了这样的信息: 在此处输入图片说明

Hir*_*hel 6

问题是您正在尝试通过 AJAX 加载文件,而您无法按照您尝试的方式进行加载。

if (file_exists($fileurl)) {
    return Response::download($fileurl, 'Photos.zip', array('Content-Type: application/octet-stream','Content-Length: '. filesize($fileurl)))->deleteFileAfterSend(true);
} else {
    return ['status'=>'zip file does not exist'];
}
Run Code Online (Sandbox Code Playgroud)

将您的javascript更改为:

let xhr = new XMLHttpRequest(),  self = this;
window.location = window.location.origin+'/download-file/' + this.selected
Run Code Online (Sandbox Code Playgroud)

希望这对你有帮助!