ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
>[danger] 七牛云图片上传封装类 ``` composer require qiniu/php-sdk ``` ```php <?php // 本文件放入TP6.0的extend目录下 extend/Qiniu.php use Qiniu\Auth; use Qiniu\Storage\UploadManager; // 设置配置参数 // Qiniu::setConfig([ // 'bucket' => 'xxxxx', // 'domain' => 'https://test.itqaq.com', // 'accessKey' => 'l_OnndRIVj17ZwIKMOZBLorh5dK4xxxxxxx', // 'secretKey' => '7fXF7wbOWcC5pUJKmGz3N8xxxxxxxxxxxxx', // ]); // 执行上传 // Qiniu::upload('img', 'art/thumb'); // 上传成功 $arr // 'result' =>true // 'msg' => 上传成功 // 'path' => 带域名的图片URL // // 上传失败 $arr // 'result' => false // 'msg' => 错误信息 /** * 七牛云封装类 * composer require qiniu/php-sdk * * @author liang <23426945@qq.com> * @version 1.0.0 * @datetime 2020-07-20 * @homepage www.itqaq.com */ class Qiniu { private static $bucket; private static $domain; private static $accessKey; private static $secretKey; /** * 私有化构造方法 * 禁止类在外部被实例化 */ private function __construct(){} /** * 设置七牛云配置参数 */ public static function setConfig($config) { // 存储空间名称 self::$bucket = $config['bucket']; // 存储空间对应的域名 self::$domain = $config['domain']; // 用于签名的公钥 AK self::$accessKey = $config['accessKey']; // 用于签名的私钥 SK self::$secretKey = $config['secretKey']; } /** * 文件上传到七牛云 */ public static function upload($field, $dirname = '') { // 捕获异常 try { // 此时可能会报错 // 比如:上传的文件过大,超出了配置文件中限制的大小 $file = request()->file($field); // 如果表单没有设置文件上传需要的编码 $file始终是null if (is_null($file)) throw new \think\Exception('没有文件上传,请检查当前是否为post请求并且是否设置了编码: enctype="multipart/form-data"'); } catch (\think\Exception $e) { // 获取异常错误信息 $errMsg = $e->getMessage(); // 上传失败,返回错误信息 return self::_rtnData(false, self::_chinese($errMsg)); } // 临时文件路径 $tmpName = $file->getRealPath(); // 原始文件后缀名 $ext = $file->getOriginalExtension(); // 初始化鉴权对象 $auth = new Auth(self::$accessKey, self::$secretKey); // 生成上传Token $token = $auth->uploadToken(self::$bucket); // 上传管理类 构建UplaodManager对象 $uploadMgr = new UploadManager(); // 目录名 if ($dirname != '') $dirname .= '/'; // 随机文件名 $path = $dirname . md5(microtime(true) . mt_rand(1, 1e9)) . '.' . $ext; // 执行文件上传到七牛云 $info = $uploadMgr->putFile($token, $path, $tmpName); // 上传到七牛云后的路径 $qiniuPath = self::$domain . '/' . $info[0]['key']; // 返回上传成功的状态信息 return self::_rtnData(true, '上传成功', $qiniuPath); } /** * 文件上传返回结果数组 */ private static function _rtnData(bool $result, $msg = null, $path = null) { // 过滤掉值为null的数组元素 return array_filter(compact('result', 'msg', 'path'), function($v){ return !is_null($v); }); } /** * 英文转为中文 */ private static function _chinese($msg) { $data = [ // 上传错误信息 'unknown upload error' => '未知上传错误!', 'file write error' => '文件写入失败!', 'upload temp dir not found' => '找不到临时文件夹!', 'no file to uploaded' => '没有文件被上传!', 'only the portion of file is uploaded' => '文件只有部分被上传!', 'upload File size exceeds the maximum value' => '上传文件大小超过了最大值!', 'upload write error' => '文件上传保存错误!', ]; return $data[$msg] ?? $msg; } /** * 私有化克隆方法 * 禁止类的实例在外部被克隆 */ private function __clone(){} } ```