如何在laravel中从S3下载文件夹

yvt65v4c  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(141)

我想从S3下载一个zip文件夹。
$zip =

new \ZipArchive();
$zipfilename = sys_get_temp_dir().'\Admissionform_'.$school_id.'_'.$formfor_id.'.zip';
$zip->open($zipfilename, \ZipArchive::CREATE);

$s3 = Storage::disk('s3');
if ($s3->exists($Mainpath)) {
$file = Files::select('path', 'extension')->find($file_id);
$pathToFile = $file->path;
$content = $s3->get($pathToFile);
$zip->addFromString($zipfilename.$filename, file_get_contents($pathToFile));
}
$zip->close();
header('Content-disposition: attachment; filename='.$filename.'.zip');
header('Content-type: application/zip');
readfile($zipfilename);

字符串
如何向前发展?

42fyovps

42fyovps1#

你的代码中有一些问题,它丢失了:
在php中导入所需的类,初始化变量并设置正确的路径zip存档。这里是代码

use Illuminate\Support\Facades\Storage;
use App\Models\Files; // Replace 'App\Models\Files' with the actual namespace of your Files model if it's different.

// Initialize the filename
$filename = 'AdmissionForm_' . $school_id . '_' . $formfor_id;

$zip = new \ZipArchive();
$zipfilename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename . '.zip';
$zip->open($zipfilename, \ZipArchive::CREATE);

$s3 = Storage::disk('s3');
if ($s3->exists($Mainpath)) {
    $file = Files::select('path', 'extension')->find($file_id);
    $pathToFile = $file->path;
    $content = $s3->get($pathToFile);
    // Add the file to the zip using its basename as the filename within the zip
    $zip->addFromString(basename($pathToFile), $content);
}
$zip->close();

// Set the correct headers to force download the zip file
header('Content-disposition: attachment; filename=' . $filename . '.zip');
header('Content-type: application/zip');
readfile($zipfilename);

字符串
确保将'App\Models\Files'替换为Files模型的正确命名空间。此外,请确保您已在Laravel应用程序中正确设置了S3配置,并且您具有访问S3存储桶和要下载的文件的必要权限。
通过这些更改,更正后的代码现在应该允许您从S3下载zip文件形式的文件夹。

相关问题