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实现笔记

相关推荐
郑州光合科技余经理8 小时前
本地生活服务系统:模块边界与结算字段怎么拆
java·开发语言·前端·后端·系统架构·uni-app·php
2601_9620725011 小时前
网络安全防护指南:筑牢网络安全防线(510)
安全·web安全·php
Patrick在香港12 小时前
Python 拉取城巴开放数据:406 条路线,香港岛巴士网络的数字画像
网络·python·数据分析·php·数据可视化·香港·开放数据
吴声子夜歌16 小时前
Java——开发中通用的方法和准则(二)
java·开发语言·php
2601_9620654917 小时前
PHP For 循环
android·java·php
2601_9620654918 小时前
interface GigabitEthernet0/0/0
服务器·php·apache
虎王物联18 小时前
PHP Swoole实现物联网MQTT数据订阅与WebSocket实时推送
物联网·mqtt·websocket·php·swoole
XR1234567881 天前
办公网自主创新建设怎么选?信创办公场景的选型逻辑
开发语言·php
CRMEB1 天前
不懂设计也能有精美商城?CRMEB 主题广场与可视化装修的“千店千面“实操
人工智能·ai·小程序·开源·php
梦梦代码精1 天前
《LikeShop全产品技术硬核拆解:ThinkPHP8+Vue3+UniApp架构,私有化部署与二次开发实战指南》
java·低代码·系统架构·php·开源软件