在Laravel中压缩和下载Amazon S3存储桶文件和文件夹

时间:2019-02-24 19:51:53

标签: laravel amazon-s3 zip zipper

是否有一种方法可以在Laravel中一起压缩和下载Amazon S3存储桶中的文件和文件夹?我想将图片中的三个文件夹和一个文件压缩在一起并下载

enter image description here

2 个答案:

答案 0 :(得分:1)

这是路由文件中的半成品解决方案。希望能帮助到你。 https://flysystem.thephpleague.com/docs/adapter/zip-archive/

    composer require league/flysystem-ziparchive

我把它放在routes / web.php中只是为了玩。

<?php   
    use Illuminate\Support\Facades\Storage;
    use League\Flysystem\Filesystem;
    use League\Flysystem\ZipArchive\ZipArchiveAdapter;

    Route::get('zip', function(){

        // see laravel's config/filesystem.php for the source disk
        $source_disk = 's3';
        $source_path = '';

        $file_names = Storage::disk($source_disk)->files($source_path);

        $zip = new Filesystem(new ZipArchiveAdapter(public_path('archive.zip')));

        foreach($file_names as $file_name){
            $file_content = Storage::disk($source_disk)->get($file_name);
            $zip->put($file_name, $file_content);
        }

        $zip->getAdapter()->getArchive()->close();

        return redirect('archive.zip');

    });

您肯定要做一些与将其放入公共目录不同的事情。也许直接将其作为下载流出或保存在更好的位置。随时发表评论/问题,我们可以讨论。

答案 1 :(得分:0)

在查看了一些解决方案之后,我通过使用https://github.com/maennchen/ZipStream-PHP将zip直接流式传输到客户端来完成以下操作:

if ($uploads) {

        return response()->streamDownload(function() use ($uploads) {

            $opt = new ArchiveOptions();

            $opt->setContentType('application/octet-stream');

            $zip = new ZipStream("uploads.zip", $opt);


            foreach ($uploads as $upload) {
                try {
                    $file = Storage::readStream($upload->path);
                    $zip->addFileFromStream($upload->filename, $file);
                }
                catch (Exception $e) {
                    \Log::error("unable to read the file at storage path: $upload->path and output to zip stream. Exception is " . $e->getMessage());
                }

            }

            $zip->finish();
        }, 'uploads.zip');
}