【问题标题】:Zipping and downloading Amazon S3 bucket files and folders in Laravel在 Laravel 中压缩和下载 Amazon S3 存储桶文件和文件夹
【发布时间】:2019-07-18 05:56:10
【问题描述】:

有没有办法在 Laravel 中一起压缩和下载 Amazon S3 存储桶中的文件和文件夹?我想把图片中的三个文件夹和一个文件压缩在一起下载

【问题讨论】:

  • 你想要它一次或作为 laravel 中的一项功能来压缩 s3 文件?
  • 作为 laravel 中的一个功能

标签: laravel amazon-s3 zip zipper


【解决方案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');

    });

您肯定会想做一些不同的事情,而不仅仅是将它放在公共目录中。也许直接将其作为下载流出来或将其保存在更好的地方。随时发表评论/问题,我们可以讨论。

【讨论】:

  • 文件正在压缩,但路径内的文件夹没有......在三个文件夹中,还有其他文件夹与文件......只有文件被压缩而不是文件夹
  • @TauseefMamun 在我的解决方案中我使用了 files() ...有一个递归版本 allfiles()
  • @TauseefMamun 看看我对这个问题的回答(不是最佳答案)...stackoverflow.com/questions/31316543/…
  • @TarekAdam 有没有办法将 zip 也保存在 S3 中?
  • @user1670816 将public_path('archive.zip') 更改为app_path('archive.zip') 然后使用这两行Storage::disk('s3')-&gt;writeStream('archive2.zip', Storage::readStream('archive.zip')); Storage::disk('local')-&gt;delete('archive.zip'); 然后重定向到其他地方,因为redirect('archive.zip') 将不存在。基本上这是在本地创建一个 zip 并将其推到 s3。抱歉,我无法在 s3 上构建 zip,也许如果您发布一个新问题,有人会做得更好。仅供参考,您需要在 project/config/filesystems.php 中配置 s3
【解决方案2】:

在查看了一些解决方案后,我通过使用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');
}

【讨论】:

  • 最佳答案 IMO,因为接受的答案较慢,并且需要您处理公共目录上的存储。
猜你喜欢
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多