前言
最近在项目开发的过程中需要对远程服务器上的文件进行打包下载,由于没有找到其他的方法,暂时想到一种思路来实现功能。
1.先把远程服务器上的文件保存到本地服务器上的指定文件夹中。
2.对该文件夹进行压缩下载其中的所有文件。
实现方式
1.安装 guzzle 组件。
安装 guzzle 组件需要先安装 composer
安装composer
2.使用 composer 安装 guzzle
php composer.phar require guzzlehttp/guzzle
或者
composer require guzzlehttp/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文件
}
}