thinkphp5 tp5 七牛云 上传图片
七牛sdk地址https://files.cnblogs.com/files/zonglonglong/qiniu-php-sdk-7.2.2.rar
首先下载php的sdk将文件夹放到vendor
然后在tp5的配置文件里加上
// +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- return [ // +---------------------------------------------------------------------- // | 七牛云设置,zll这里是七牛云的配置,七牛云上传用的就是这四个参数 // +---------------------------------------------------------------------- 'ACCESSKEY' => '*******',//你的accessKey 'SECRETKEY' => '*****',//你的secretKey 'BUCKET' => '***',//上传的空间 'DOMAIN'=>'****.bkt.clouddn.com',//空间绑定的域名 // +---------------------------------------------------------------------- // | 应用设置 // +---------------------------------------------------------------------- // 应用命名空间 'app_namespace' => 'app', // 应用调试模式 'app_debug' => true, // 应用Trace 'app_trace' => false,
然后写php文件,引入七牛的sdk
<?php namespace app\index\controller; use think\Db; use think\Controller; use think\Session; use Qiniu\Auth as Auth; use Qiniu\Storage\BucketManager; use Qiniu\Storage\UploadManager; class Base extends Controller { public function _initialize(){ } /** * 图片上传 * @return String 图片的完整URL */ public function upload() { if(request()->isPost()){ $file = request()->file('image'); // 要上传图片的本地路径 $filePath = $file->getRealPath(); $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION); //后缀 //获取当前控制器名称 // $controllerName=$this->getContro(); // 上传到七牛后保存的文件名 $key =substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; require_once APP_PATH . '/../vendor/qiniu-php-sdk-7.2.2/autoload.php'; // 需要填写你的 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) { return ["err"=>1,"msg"=>$err,"data"=>""]; } else { //返回图片的完整URL return json(["err"=>0,"msg"=>"上传完成","data"=>($domain . $ret['key'])]); } } } }
破罐子互摔