thinkphp集成七牛云存储

作者:谢高升 发布:2019-05-31 浏览:2357次

首先去申请七牛云存储的下面是代码部分

#安装七牛云插件
composer  require qiniu/php-sdk
<?php
/**
 * 七牛云
 */
namespace app\extra;
use Qiniu\Auth; //七牛鉴权使用
use Qiniu\Storage\UploadManager; //七牛上传使用
class UploadFile {
    protected $domain;
    protected $bucket;
    protected $token;
    protected $ACCESS_KEY ; //七牛ACCESS_KEY
    protected $SECRET_KEY ; //七牛SECRET_KEY
    public function __construct() {
        $this->domain = config('qiniu.DOMAIN');
        $this->bucket = config('qiniu.BUCKET');
        $this->ACCESS_KEY = config('qiniu.ACCESS_KEY');
        $this->SECRET_KEY = config('qiniu.SECRET_KEY');
        $auth = new Auth( $this->ACCESS_KEY, $this->SECRET_KEY);
        // 生成上传Token
        $this->token = $auth->uploadToken($this->bucket);
    }

    /**
     * 上传
     * @param $file
     * @return array
     * @throws \Exception
     */
    public function uploadOne($file) {
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($this->token, $file['name'], $file['tmp_name']);
        if ($err !== null) {
            return ['err' => 1, 'msg' => $err, 'data' => ''];
        } else {
            //返回文件的完整URL
            return ['err' => 0, 'msg' => '上传完成', 'data' => ($this->domain . $ret['key'])];
        }
    }
}