Laravel中使用MinIO进行文件操作及ZIP解压

Laravel中使用MinIO进行文件操作及ZIP解压指南

介绍

在本指南中,我们将详细介绍如何在laravel框架中操作minio,包含方法有:桶列表,创建桶,修改桶,上传文件,删除文件,生成直传链接,解压zip的php脚本

docker布署单节点单磁盘的MinIO服务

1.拉取MinIO最新稳定镜像
shell 复制代码
docker pull quay.io/minio/minio
2.创建环境变量文件
text 复制代码
# 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 environment

MINIO_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.创建并运行容器
shell 复制代码
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.验证容器状态
shell 复制代码
docker logs minio

该命令应返回类似以下的输出:

shell 复制代码
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-me

Command-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-me

Documentation: https://minio.org.cn/docs/minio/container/index.html
5.浏览器中输入http://localhost:9001 来访问MinIO Web控制台

Laravel框架使用minio

安装三方库以及配置

composer.json 添加

json 复制代码
{
    "require": {
      "tanghengzhi/aws-sdk-php-laravel": "^3.7"
    }
}
shell 复制代码
php composer.phar update
或者
composer update

配置config/app.php 和 AWS Facade

php 复制代码
'providers' => array(
        // ...
        Aws\Laravel\AwsServiceProvider::class,
    )
php 复制代码
'aliases' => array(
        // ...
        'AWS' => Aws\Laravel\AwsFacade::class,
    )

生成configuration文件

shell 复制代码
php artisan vendor:publish  --provider="Aws\Laravel\AwsServiceProvider"

config/aws.php的配置

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
php 复制代码
    //创建桶 $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 复制代码
<?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应用中实现高性能的文件存储和管理功能。

相关推荐
hbh112233abc4 小时前
实现 think/queue 日志分离
php·thinkphp·queue
黑客K-ing6 小时前
网络安全名词解释
开发语言·网络·安全·网络安全·php
23zhgjx_ywz9 小时前
HCIP快速生成树 RSTP
开发语言·php
文人sec11 小时前
泷羽sec学习打卡-Windows基础virus
windows·学习·安全·web安全·php
2401_8576363912 小时前
工位管理智能化:Spring Boot企业级平台
数据库·spring boot·php
数据小小爬虫13 小时前
PHP爬虫快速获取京东商品详情(代码示例)
开发语言·爬虫·php
小春学渗透15 小时前
DAY111PHP开发框架&THIKNPHP&反序列化&POP利用链&RCE执行&文件删除
java·开发语言·安全·php·mvc·代码审计
23zhgjx-hyh20 小时前
RSTP的配置
linux·服务器·php
饮长安千年月20 小时前
CTF记录
python·网络安全·php
ac-er88881 天前
PHP API的数据交互类型设计
开发语言·php