创建并下载包含多个文件的 zip,无需将 zip 文件保存在服务器上(PHP 和 laravel)

问题描述 投票:0回答:1

我的 Laravel 服务器上有几个文件。我已经可以单独下载它们了。不过,我想将许多文件压缩成一个 zip 文件,然后只下载 zip 文件。

我知道我可以在数据库中创建一个新的 zip 文件并添加所有文件,但我不喜欢将 zip 文件保留在数据库中,因为它会占用太多空间。

理想情况下,当用户单击用户界面(网站)上的按钮并下载该文件时,服务器会创建 zip 文件,而不将其存储在服务器上。

一个可能的解决方案是存储 zip 并在 10 分钟后将其删除,例如,但我无法确定它是否已经下载。

你能想出更好的方法吗?

php laravel download zip
1个回答
0
投票

公共函数profilesPdfGenerate(请求$request) { $pdfFiles = []; $时间=时间(); if(count($request->selectedIds)){ $profiles = Profile::whereIn('id',$request->selectedIds)->get(); }其他{ $profiles = Profile::get(); } foreach($profiles as $key => $profile){ $view = view('admin.profiles.index-pdf')->with(compact('profile')); $html = $view->render(); $pdf = PDF::loadHTML($html); $customPaper = 数组(0,0,900,900); $sheet = $pdf->setPaper($customPaper, '横向'); $pdfFiles[$profile->first_name.'-'.$profile->last_name.'-'.$key.'.pdf'] = $sheet->output(); $zip = 新的 ZipArchive; /* 为 zip 创建一个临时文件 */ $zipPath = tempnam(sys_get_temp_dir(), 'profiles'); if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) { foreach ($pdfFiles as $fileName => $pdfData) { $zip->addFromString($fileName, $ pdf数据); $zip->close(); $base64Zip = base64_encode(file_get_contents($zipPath));返回响应()->json(['base64_zip' => $base64Zip]); } else { return response()->json(['error' => '创建 zip 文件失败'], 500); } }

© www.soinside.com 2019 - 2024. All rights reserved.