Laravel8中保存远程文件到本地文件夹并且打包下载该文件夹中的所有文件

前言

最近在项目开发的过程中需要对远程服务器上的文件进行打包下载,由于没有找到其他的方法,暂时想到一种思路来实现功能。
1.先把远程服务器上的文件保存到本地服务器上的指定文件夹中。
2.对该文件夹进行压缩下载其中的所有文件。

实现方式

1.安装 guzzle 组件。
安装 guzzle 组件需要先安装 composer
安装composer
2.使用 composer 安装 guzzle
php composer.phar require guzzlehttp/guzzle
或者
composer require guzzlehttp/guzzle

使用方法

guzzle 文档

代码实现方式

<?php
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;
    //打包下载
    public function downLoadPackage()
    {
        //1.先把远程文件下载到本地文件夹中
        $fileData = [
            "http://xxxxx/files/upload/15/202105131728498439870.txt",
            "http://xxxxx/files/upload/15/202105131728548576292.xlsx",
            "http://xxxxx/files/upload/15/202105131749348716015.png",
            "http://xxxxx/files/upload/15/202105131749499708495.jpg",
            "http://xxxxx/files/upload/15/202105131750001763090.jpeg",
        ];
        $client = new Client(['verify' => false]); //忽略SSL错误
        $judge = false; //判断是否保存完毕
        foreach ($fileData as $val) {
            $file_temp_path = 'document/remoteFiles/' . pathinfo($val)['basename']; //保存文件地址+原始文件名
            $tempData = $client->request('get', $val)->getBody()->getContents();
            $judge = Storage::disk('public')->put($file_temp_path, $tempData); //storage/app/public/document/remoteFiles文件保存地址
        }
        if ($judge) {
            //2.打包下载本地文件夹
            //初始化zip 名字
            $zipName = 'file.zip';
            $zip_file = str_replace("\\", '/', storage_path('app/public/document/')) . $zipName; //storage/app/public/document/file.zip
            $zip = new \ZipArchive();
            $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
            //将被压缩文件夹
            $path = str_replace("\\", '/', storage_path('app/public/document/remoteFiles/')); //storage/app/public/document/remoteFiles
            //迭代器
            $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
            foreach ($files as $file) {
                //跳过所有子目录
                if (!$file->isDir()) {
                    //获取文件路径
                    $filePath = $file->getRealPath();
                    //获取文件名
                    $fileName = $file->getFilename();
                    $zip->addFile($filePath, $fileName);
                }
            }
            $zip->close();
            return response()->download($zip_file, $zipName); //下载生成的zip文件
        }
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值