tp5 图片上传到七牛云

1-安装七牛云官方SDK

composer require qiniu/php-sdk -vvv

2-七牛云配置

1----config文件

//七牛云配置
    'qiniu' => [
        'accessKey' => '.......................................',
        'secretKey' => '.......................................',
        'domain' => '.............................',//域名地址
        'bucket' => '......',//空间名称
        'zone'=> 'south_china'//区域
    ],

3-  对应的控制器

use Qiniu\Auth;
require 'vendor/qiniu/php-sdk/autoload.php';  //引入自动加载类
use Qiniu\Storage\UploadManager; //实例化上传类




public function add(){
      $file = request()->file('img');
                // 要上传图片的本地路径
                $filePath = $file->getRealPath();
                $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
                // 上传到七牛后保存的文件名
                $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
                // 需要填写你的 Access Key 和 Secret Key
                // 构建鉴权对象
                $accessKey =config("qiniu")["accessKey"];
                $secretKey =config("qiniu")["secretKey"];
                $auth=new Auth($accessKey,$secretKey);
                // 要上传的空间
                $bucket =config("qiniu")["bucket"];
                //域名
                $domain=config("qiniu")["domain"];
                $token = $auth->uploadToken($bucket);
                // 初始化 UploadManager 对象并进行文件的上传
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传
                list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
                if ($err !== null) {
                    return ["err"=>1,"msg"=>$err,"data"=>""];
                } else {
                    //返回图片的完整URL
                    $imgPath=$domain.'/'.$key;
                    //赋值
                    $data["thumb_url"] = $imgPath;
                    $data = Db::name('top_bar')->insert($data);
                    $this->redirect("/admin/topbar/index");
                }


}

猜你喜欢

转载自blog.csdn.net/qq_37138818/article/details/81164115