thinkphp5调用七牛云SDK上传文件

1.先在verdor里新建一个文件夹: Qiniu

2.将SDK压缩包中的文件全部解压到Qiniu文件夹中

3.在Controller中,引用类

vendor('Qiniu.autoload');
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
  • 1
  • 2
  • 3
  • 4

4.在config.php中添加配置

'ACCESSKEY' => '',//你的accessKey
'SECRETKEY' => '',//你的secretKey
'BUCKET' => '',//上传的空间
'DOMAIN'=>'',//空间绑定的域名
  • 1
  • 2
  • 3
  • 4

5.上传操作的函数

$file = request()->file('image');
// 要上传图片的本地路径
$filePath = $file->getRealPath();
$ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
//获取当前控制器名称
$controllerName = 'index';
// 上传到七牛后保存的文件名
$key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext;
// 需要填写你的 Access Key 和 Secret Key
$accessKey = config('ACCESSKEY');
$secretKey = config('SECRETKEY');
// 构建鉴权对象
$auth = new Auth($accessKey, $secretKey);
// 要上传的空间
$bucket = config('BUCKET');
$domain = config('DOMAINImage');
$token = $auth->uploadToken($bucket);
// 初始化 UploadManager 对象并进行文件的上传
$uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
if ($err !== null) {
    echo ["err"=>1,"msg"=>$err,"data"=>""];
} else {
    //返回图片的完整URL
    var_dump($ret);
}

猜你喜欢

转载自blog.csdn.net/php_lzr/article/details/79695428