**引入七牛云扩展包** ```php composer require qiniu/php-sdk ``` **创建文件上传配置文件 `config/upload.php`** ```php <?php // 文件上传配置 return [ 'qiniu' => [ // 存储空间名称 'bucket' => 'itqaq', // 存储空间的对应域名 'domain' => '//qbx51pqrr.bkt.clouddn.com', // 用于签名的公钥 AccessKey 'accessKey' => 'l_OnndRIVj17ZwIKMOZBLorh5dK4BKIxxxxxx', // 用于签名的私钥 SecretKey 'secretKey' => '7fXF7wbOWcC5pUJKmGz3N8DU6ZB7u3exxxxxx', ], ]; ``` **七牛云文件上传封装** ```php <?php namespace app\admin\controller; use think\facade\Config; use Qiniu\Auth; use Qiniu\Storage\UploadManager; /** * 七牛云封装类 */ class Qiniu { /** * 文件上传到七牛云 * @return 在七牛云上的文件名 */ public static function upload($field = '', $dirname = '') { // 存储空间名称 $bucket = Config::get('upload.qiniu.bucket'); // 存储空间对应的域名 $domain = Config::get('upload.qiniu.domain'); // 用于签名的公钥 AK $accessKey = Config::get('upload.qiniu.accessKey'); // 用于签名的私钥 SK $secretKey = Config::get('upload.qiniu.secretKey'); $file = request()->file($field); if ($file) { // 临时文件路径 $tmpName = $file->getRealPath(); // 初始化鉴权对象 $auth = new Auth($accessKey, $secretKey); // 生成上传Token $token = $auth->uploadToken($bucket); // 上传管理类 构建UplaodManager对象 $uploadMgr = new UploadManager(); // 原始文件后缀名 $ext = $file->getOriginalExtension(); // 目录名 if ($dirname != '') $dirname .= '/'; // 随机文件名 $path = $dirname . md5(microtime(true) . mt_rand(1, 1e9)) . '.' . $ext; $info = $uploadMgr->putFile($token, $path, $tmpName); // 上传到七牛云后的新名称 return $domain . '/' . $info[0]['key']; } else { return '没有文件上传'; } } } ``` **使用示例** ```php //qbx51pqrr.bkt.clouddn.com/article/content/1e0ba811a443c5a38e1e615f35526bc3.jpg \app\admin\controller\Qiniu::upload('pic', 'article/content'); ```