Fastadmin中使用阿里云oss

在Fastadmin中使用阿里云oss实现笔记

目录

安装依赖库

Oss配置

封装oss操作

测试调用

总结


安装依赖库

命令如下:

bash 复制代码
composer require aliyuncs/oss-sdk-php

安装后,版本如下:

Oss配置

在application/extra目录创建oss.php,设置oss配置内容:

php 复制代码
<?php

// +----------------------------------------------------------------------
// | 阿里云OSS存储配置
// +----------------------------------------------------------------------
return [
    
        'accessKeyId'      => '',           // AccessKey ID
        'accessKeySecret'  => '',           // AccessKey Secret
        'endpoint'         => '',           // OSS节点地址,如:oss-cn-hangzhou.aliyuncs.com
        'bucket'           => '',           // OSS存储空间名称
        'ssl'              => false,        // 是否使用HTTPS
        'customDomain'     => '',           // 自定义域名,如:cdn.example.com
    ],
];

封装oss操作

在common/library中创建Oss.php文件。

封装上传、删除等文件操作。

代码如下:

php 复制代码
<?php

namespace app\common\library;

use OSS\OssClient;
use OSS\Core\OssException;
use think\Config;

/**
 * 阿里云OSS存储类
 */
class Oss
{
    protected $config = [];
    protected $ossClient = null;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->config = config('oss');
        $this->initClient();
    }

    /**
     * 初始化OSS客户端
     */
    protected function initClient()
    {
        if (!$this->config['accessKeyId'] || !$this->config['accessKeySecret'] || !$this->config['endpoint']) {
            throw new \Exception('OSS配置不完整');
        }

        try {
            $this->ossClient = new OssClient(
                $this->config['accessKeyId'],
                $this->config['accessKeySecret'],
                $this->config['endpoint']
            );
        } catch (\Exception $e) {
            throw new \Exception('初始化OSS客户端失败: ' . $e->getMessage());
        }
    }

    /**
     * 上传文件
     * @param string $filePath 本地文件路径
     * @param string $object 上传到OSS后的文件路径
     * @return array 返回上传结果和访问链接
     */
    public function uploadFile($filePath, $object = '')
    {
        if (!file_exists($filePath)) {
            throw new \Exception('文件不存在');
        }

        if (empty($object)) {
            $object = $this->generateObjectKey($filePath);
        }

        try {
            $result = $this->ossClient->uploadFile($this->config['bucket'], $object, $filePath);
            
            $url = $this->getFileUrl($object);
            
            return [
                'success' => true,
                'url'     => $url,
                'object'  => $object,
                'info'    => $result
            ];
        } catch (OssException $e) {
            throw new \Exception('文件上传失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除文件
     * @param string $object 文件在OSS中的路径
     * @return bool 删除是否成功
     */
    public function deleteFile($object)
    {
        if (empty($object)) {
            throw new \Exception('文件路径不能为空');
        }

        try {
            $this->ossClient->deleteObject($this->config['bucket'], $object);
            return true;
        } catch (OssException $e) {
            throw new \Exception('文件删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 批量删除文件
     * @param array $objects 文件路径数组
     * @return array 返回删除结果
     */
    public function deleteFiles($objects)
    {
        if (empty($objects) || !is_array($objects)) {
            throw new \Exception('文件路径数组不能为空');
        }

        try {
            $result = $this->ossClient->deleteObjects($this->config['bucket'], $objects);
            return [
                'success' => true,
                'deleted' => $result
            ];
        } catch (OssException $e) {
            throw new \Exception('批量删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取文件URL
     * @param string $object 文件在OSS中的路径
     * @return string 文件访问链接
     */
    public function getFileUrl($object)
    {
        if (empty($object)) {
            return '';
        }

        $protocol = $this->config['ssl'] ? 'https://' : 'http://';
        
        if ($this->config['customDomain']) {
            return $protocol . $this->config['customDomain'] . '/' . ltrim($object, '/');
        } else {
            $endpoint = str_replace(['http://', 'https://'], '', $this->config['endpoint']);
            return $protocol . $this->config['bucket'] . '.' . $endpoint . '/' . ltrim($object, '/');
        }
    }

    /**
     * 生成文件路径
     * @param string $filePath 原始文件路径
     * @return string 生成的OSS路径
     */
    protected function generateObjectKey($filePath)
    {
        $filename = basename($filePath);
        $suffix = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        $year = date('Y');
        $month = date('m');
        $day = date('d');
        
        $object = "{$year}/{$month}/{$day}/" . uniqid() . '.' . $suffix;
        
        return $object;
    }

    /**
     * 检查文件是否存在
     * @param string $object 文件路径
     * @return bool 是否存在
     */
    public function fileExists($object)
    {
        if (empty($object)) {
            return false;
        }

        try {
            return $this->ossClient->doesObjectExist($this->config['bucket'], $object);
        } catch (OssException $e) {
            return false;
        }
    }

    /**
     * 获取配置
     * @return array 配置数组
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * 获取OSS客户端实例
     * @return OssClient
     */
    public function getClient()
    {
        return $this->ossClient;
    }
}

测试调用

在application/api/controller中创建OssTest控制器

代码如下:

php 复制代码
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Oss;

/**
 * OSS测试控制器
 */
class OssTest extends Api
{
    protected $noNeedLogin = ['*'];
    
    protected $noNeedRight = ['*'];

    /**
     * 上传文件测试
     */
    public function upload()
    {
        $file = request()->file('file');
        if (!$file) {
            $this->error('请上传文件');
        }

        try {
            $oss = new Oss();
            $result = $oss->uploadFile($file->getRealPath());
            
            $this->success('上传成功', $result);
        } catch (\Exception $e) {
            $this->error('上传失败: ' . $e->getMessage());
        }
    }

    /**
     * 删除文件测试
     */
    public function delete()
    {
        $object = $this->request->post('object');
        if (!$object) {
            $this->error('请提供文件路径');
        }

        try {
            $oss = new Oss();
            $result = $oss->deleteFile($object);
            
            $this->success('删除成功');
        } catch (\Exception $e) {
            $this->error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取文件URL
     */
    public function getUrl()
    {
        $object = $this->request->post('object');
        if (!$object) {
            $this->error('请提供文件路径');
        }

        try {
            $oss = new Oss();
            $url = $oss->getFileUrl($object);
            
            $this->success('获取成功', ['url' => $url]);
        } catch (\Exception $e) {
            $this->error('获取失败: ' . $e->getMessage());
        }
    }
}

总结

在Fastadmin中使用阿里云oss实现笔记

相关推荐
sthnyph2 小时前
防火墙安全策略(基本配置)
服务器·php·apache
不写八个14 小时前
PHP教程004:php链接mysql数据库
数据库·mysql·php
sg_knight19 小时前
Docker环境下的MinIO安装,以及如何正确配置数据持久化(避坑篇)
运维·docker·容器·minio·ftp·cos·oss
cch891819 小时前
PHP vs Go:Web开发选谁更胜一筹?
前端·golang·php
sg_knight20 小时前
MinIO自带的Web Console管理后台怎么用?日常管理操作全解
前端·文件管理·minio·ftp·cos·oss
淼淼爱喝水20 小时前
OpenEuler 系统下 Ansible 环境部署与连通性测试完整步骤
linux·开发语言·php·openeuler
一只会跑会跳会发疯的猴子1 天前
php操作elasticsearch,亲测可用
开发语言·elasticsearch·php
我叫黑大帅1 天前
PHP 中处理图像的利器 GD库
后端·面试·php
我叫黑大帅1 天前
如何使用PHP创建图像验证码
后端·面试·php