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 上传结果信息
*/
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;
}
}
网友评论