作者:小虾米 发表时间:2017-05-28 01:08:40 类别:PHP
composer require qiniu/php-sdk
<?php
/**
* Created by PhpStorm.
* User: xieming
* Date: 2017/5/27
* Time: 20:05
*/
namespace app\index\model;
use think\Model;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Upload extends Model{
private $AccessKey;
private $SecretKey;
private $bucket;
private $auth;
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 upload($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 = time().rand(0, 9999).'.'.$extension;
//初始化UploadManager对象
$uploadManager = new UploadManager();
//文件上传
list($result, $error) = $uploadManager->putFile($token, $key, $filePath);
if ($error !== null) {
return ['errNo'=>1,'errMsg'=>'','data'=>''];
} else {
return ['errNo'=>0,'data'=>['bucket'=>$this->bucket,'key'=>$key];
}
}
/**
* 获取私有空间或使用了原图保护功能的图片文件地址
* @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;
}
}
以上只是简单实例,具体的参数处理、数据验证没有实现。如有错误之处,请留言指正,感谢。