thinkphp5上传图片到七牛云
2022-05-29ThinkPHP
日常开发中,经常会用到上传图片的功能,为了不占用服务器带宽,通常要把图片资源存放到第三方资源库,下面分享一则实例,利用thinkphp5上传图片到七牛云。
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");
}
} 很赞哦! ()
