Laravel中使用MinIO进行文件操作及ZIP解压指南
介绍
在本指南中,我们将详细介绍如何在laravel框架中操作minio,包含方法有:桶列表,创建桶,修改桶,上传文件,删除文件,生成直传链接,解压zip的php脚本
docker布署单节点单磁盘的MinIO服务
1.拉取MinIO最新稳定镜像
docker pull quay.io/minio/minio
2.创建环境变量文件
# MINIO_ROOT_USER and MINIO_ROOT_PASSWORD sets the root account for the MinIO server.
# This user has unrestricted permissions to perform S3 and administrative API operations on any resource in the deployment.
# Omit to use the default values 'minioadmin:minioadmin'.
# MinIO recommends setting non-default values as a best practice, regardless of environmentMINIO_ROOT_USER=myminioadmin
MINIO_ROOT_PASSWORD=minio-secret-key-change-me# MINIO_VOLUMES sets the storage volume or path to use for the MinIO server.MINIO_VOLUMES="/mnt/data"# MINIO_OPTS sets any additional commandline options to pass to the MinIO server.
# 例如, `--console-address :9001` sets the MinIO Console listen port
MINIO_OPTS="--console-address :9001"# MINIO_SERVER_URL sets the hostname of the local machine for use with the MinIO Server
# MinIO assumes your network control plane can correctly resolve this hostname to the local machine# Uncomment the following line and replace the value with the correct hostname for the local machine and port for the MinIO server (9000 by default).#MINIO_SERVER_URL="http://minio.example.net:9000"
3.创建并运行容器
docker run -dt \-p 9000:9000 -p 9001:9001 \-v PATH:/mnt/data \-v /etc/default/minio:/etc/config.env \-e "MINIO_CONFIG_ENV_FILE=/etc/config.env" \--name "minio_local" \minio server --console-address ":9001"
4.验证容器状态
docker logs minio
该命令应返回类似以下的输出:
Status: 1 Online, 0 Offline.
API: http://10.0.2.100:9000 http://127.0.0.1:9000
RootUser: myminioadmin
RootPass: minio-secret-key-change-me
Console: http://10.0.2.100:9001 http://127.0.0.1:9001
RootUser: myminioadmin
RootPass: minio-secret-key-change-meCommand-line: https://minio.org.cn/docs/minio/linux/reference/minio-mc.html$ mc alias set myminio http://10.0.2.100:9000 myminioadmin minio-secret-key-change-meDocumentation: https://minio.org.cn/docs/minio/container/index.html
5.浏览器中输入http://localhost:9001 来访问MinIO Web控制台
Laravel框架使用minio
安装三方库以及配置
composer.json 添加
{"require": {"tanghengzhi/aws-sdk-php-laravel": "^3.7"}
}
php composer.phar update
或者
composer update
配置config/app.php 和 AWS Facade
'providers' => array(// ...Aws\Laravel\AwsServiceProvider::class,)
'aliases' => array(// ...'AWS' => Aws\Laravel\AwsFacade::class,)
生成configuration文件
php artisan vendor:publish --provider="Aws\Laravel\AwsServiceProvider"
config/aws.php的配置
return ['version' =>'latest','region' => env('AWS_REGION', 'ap-south-1'),'endpoint' => env('AWS_ENDPOINT', 'http://127.0.0.1:9000'),'use_path_style_endpoint' =>true,'credentials' => ['key' => env('AWS_KEY', 'key'),'secret' => env('AWS_SECRET', 'secret'),],'Ses' => ['region' => env('AWS_SES_REGION', 'ap-south-1'),],'Bucket' => env('AWS_SES_Bucket', 'Bucket'),
];
使用Laravel操作minio
//创建桶 $buket 桶名称public function createBucket($buket){$s3 = AwsFacade::createClient('s3');$s3->createBucket(['Bucket' => $buket]); //创建桶return true;}//删除文件 url为创建接口返回的完整路径public function deleteFile($url){if (empty($url)) return false;$s3 = AwsFacade::createClient('s3');$s3->deleteObject(['Bucket' => config('aws.Bucket'), //存储桶名称'Key' => strrchr($url, '/'), //文件名 去掉time-management]);return true;}//复制文件 url为创建接口返回的完整路径public function copyFile($sourceUrl){if (empty($url)) return false;$s3 = AwsFacade::createClient('s3');#文件扩展名$extend = strrchr($sourceUrl, '.');# 自定义文件名$fileName = date('Ymd') . '-' . uniqid() . $extend;$s3_return = $s3->copyObject(['Bucket' => config('aws.Bucket'), //存储桶名称'CopySource' => $sourceUrl,'Key' => $fileName,]);if ($s3_return['@metadata']['statusCode'] == 200) {return $s3_return['@metadata']['effectiveUri'];} else {return false;}}//桶列表public function buketList($buket, $maxkey, $after, $prefix = ''){$s3 = AwsFacade::createClient('s3');$keys = $s3->listObjectsV2(['Bucket' => $buket,'Prefix' => $prefix,'MaxKeys' => $maxkey,'StartAfter' => $after]);return $keys['Contents'];}//创建直传链接public function presignedRequest($name){//从client中获得一个commad对象$s3Client = AwsFacade::createClient('s3');$command = $s3Client->getCommand('PutObject', ['Bucket' => config('aws.Bucket'),'Key' => $name]);// 获得一个10分钟有效期的pre-signed URL$presignedRequest = $s3Client->createPresignedRequest($command, '+10 minutes');// 获得presigned-url$presignedUrl = (string)$presignedRequest->getUri();return $presignedUrl;}
Minio zip文件解压
官方没有提供解压的Api,所以自己用php写解压脚本,传入文件名称,解压返回目录
<?php
$success = ['code' => 200,'data' => '',
];
$error = ['code' => 500,'data' => '',
];
if (empty($_POST['name'])) {$error['data'] = '系统错误';echo json_encode($error);exit();
}
//接受文件名称
$name = $_POST['name'];
//解析文件后缀和名称
$path_info = pathinfo($name);
$basename = $path_info['filename'];
//生成需要创建的文件夹名称
$mkdir_path = "/home/docker_data/minio/data/{bucket}/$basename";
$undir_path = "/home/docker_data/minio/data/{bucket}/$name";
//判断地址是否存在 拼装shell脚本
if (file_exists($mkdir_path)) {$shell = "export LANG=en_US.UTF-8;cd / && unzip -o -O GBK -d $mkdir_path $undir_path";
} else {$shell = "export LANG=en_US.UTF-8;cd / && mkdir $mkdir_path && unzip -o -O GBK -d $mkdir_path $undir_path";
}
//执行shell脚本
exec($shell, $result, $status);
if (empty($result)) {$error['data'] = '系统错误';echo json_encode($error);exit();
}
//去掉最外层文件夹名称
unset($result[0]);
if (empty($result)) {$error['data'] = '系统错误';echo json_encode($error);exit();
}
$folder = [];
//循环组装自己想要的目录
foreach ($result as $k => $v) {if (strpos($v, 'creating')) {continue;}$str = str_replace('inflating:', '', $v);$str = str_replace('creating:', '', $str);$str = str_replace('extracting:', '', $str);$str = str_replace('/home/docker_data/minio/data/{bucket}/'.$basename.'/', '', $str);$str = str_replace(' ', "", $str);$folder[] = $str;
}
$success['data'] = $folder;
echo json_encode($success);
exit();
总结
本文详细介绍了如何在Laravel框架中集成MinIO对象存储服务,并展示了如何执行基本的文件操作和ZIP文件解压。通过MinIO,开发者可以轻松地在Laravel应用中实现高性能的文件存储和管理功能。