composer安裝七牛SDK
config文件保存七牛云配置信息
Controller:
namespace app\admin\controller;
use think\Controller;
class Qiniu extends Controller {
? ? /** 上傳頁面
? ? * Created by PhpStorm.
* User: Administrator
* Date: 2019-7-26 0026
* Time: 10:34
*/
? ? public function index()
{
? ? ? ? return view();
? ? }
? ? /** 上傳圖片
? ? * Created by PhpStorm.
* User: Administrator
* Date: 2019-7-26 0026
* Time: 10:34
*/
? ? public function upload()
{
? ? ? ? if ($this->request->isPost()) {
? ? ? ? ? ? $qiniu = new \app\admin\model\Qiniu();
? ? ? ? ? ? $data = $qiniu->uploadImage('imgFile');
? ? ? ? ? ? var_dump($data);
? ? ? ? }
}
}
model:
namespace app\admin\model;
use think\Model;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Qiniu extends Model
{
? ? private $AccessKey;
? ? private $SecretKey;
? ? private $bucket;
? ? private $auth;
? ? public function __construct()
{
? ? ? ? parent::__construct();
? ? ? ? $this->AccessKey = config('qiniu.AccessKey');
? ? ? ? $this->SecretKey = config('qiniu.SecretKey');
? ? ? ? $this->bucket = config('qiniu.bucket');
? ? ? ? vendor('qiniu.php-sdk.autoload');
? ? ? ? $this->auth = new Auth($this->AccessKey, $this->SecretKey);
? ? }
? ? /**
? ? * @description 七牛上傳文件
? ? * @param string $fileName 上傳文件的name值
? ? * @param string $bucket 上傳至七牛的指定空間
? ? * @return array 上傳結(jié)果信息
? ? */
? ? public function uploadImage($fileName = '', $bucket = '')
{
? ? ? ? //文件獲取页慷、處理
? ? ? ? $file = request()->file($fileName);
? ? ? ? // 上傳文件的本地路徑
? ? ? ? $filePath = $file->getRealPath();
? ? ? ? //文件后綴
? ? ? ? $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
? ? ? ? //獲取七牛token
? ? ? ? $bucket = empty($bucket) ? $this->bucket : $bucket;
? ? ? ? $token = $this->auth->uploadToken($bucket);
? ? ? ? //上傳到七牛后保存的文件名
? ? ? ? $key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') .? rand(0, 9999) . '.' . $extension;
? ? ? ? //初始化UploadManager對象
? ? ? ? $uploadManager = new UploadManager();
? ? ? ? //文件上傳
? ? ? ? $data = $uploadManager->putFile($token, $key, $filePath);
? ? ? ? if ($data) {
? ? ? ? ? ? return json_encode(['code'=>200,'status'=>1,'msg'=>'上傳成功','data'=>$data]);
? ? ? ? } else {
? ? ? ? ? ? return json_encode(['code'=>200,'status'=>0,'msg'=>'上傳失敗']);
? ? ? ? }
}
? ? /**
? ? * 獲取私有空間或使用了原圖保護功能的圖片文件地址
? ? * @param string $url 格式:http://domain/key[文件名]?e=時間戳
? ? * @return string 可訪問的url地址:http://domain/key[文件名]?e=時間戳&token='token'
*/
? ? public function getSignedUrl($url)
{
? ? ? ? $signedUrl = $this->auth->privateDownloadUrl($url);
? ? ? ? //該url地址需要驗證是否可訪問憔足。
? ? ? ? return $signedUrl;
? ? }
}