作者寄语:
七头牛,真是七头牛,很难搞的定。
1,获取uptoken,获取方法,要使用七头牛官方的phpsdk中的auth.php这个文件,sdk自己的官方下载。先把文件名改成Auth.class.php,然后把命名空间换成你想要的。话说七头牛官方sdk的命名空间,是在是混乱的看不懂。代码如下:
<?php
namespace Home\Controller;
final class Auth
{
private $accessKey;
private $secretKey;
public function __construct($accessKey, $secretKey)
{
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
}
public function sign($data)
{
$hmac = hash_hmac('sha1', $data, $this->secretKey, true);
return $this->accessKey . ':' . base64_urlSafeEncode($hmac);
}
public function signWithData($data)
{
$data = base64_urlSafeEncode($data);
return $this->sign($data) . ':' . $data;
}
public function signRequest($urlString, $body, $contentType = null)
{
$url = parse_url($urlString);
$data = '';
if (array_key_exists('path', $url)) {
$data = $url['path'];
}
if (array_key_exists('query', $url)) {
$data .= '?' . $url['query'];
}
$data .= "\n";
if ($body !== null && $contentType === 'application/x-www-form-urlencoded') {
$data .= $body;
}
return $this->sign($data);
}
public function verifyCallback($contentType, $originAuthorization, $url, $body)
{
$authorization = 'QBox ' . $this->signRequest($url, $body, $contentType);
return $originAuthorization === $authorization;
}
public function privateDownloadUrl($baseUrl, $expires = 3600)
{
$deadline = time() + $expires;
$pos = strpos($baseUrl, '?');
if ($pos !== false) {
$baseUrl .= '&e=';
} else {
$baseUrl .= '?e=';
}
$baseUrl .= $deadline;
$token = $this->sign($baseUrl);
return "$baseUrl&token=$token";
}
public function uploadToken(
$bucket,
$key = null,
$expires = 3600,
$policy = null,
$strictPolicy = true
) {
$deadline = time() + $expires;
$scope = $bucket;
if ($key !== null) {
$scope .= ':' . $key;
}
$args = array();
$args = self::copyPolicy($args, $policy, $strictPolicy);
$args['scope'] = $scope;
$args['deadline'] = $deadline;
$b = json_encode($args);
return $this->signWithData($b);
}
/**
*上传策略,参数规格详见
*http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html
*/
private static $policyFields = array(
'callbackUrl',
'callbackBody',
'callbackHost',
'callbackBodyType',
'callbackFetchKey',
'returnUrl',
'returnBody',
'endUser',
'saveKey',
'insertOnly',
'detectMime',
'mimeLimit',
'fsizeMin',
'fsizeLimit',
'persistentOps',
'persistentNotifyUrl',
'persistentPipeline',
);
private static $deprecatedPolicyFields = array(
'asyncOps',
);
private static function copyPolicy(&$policy, $originPolicy, $strictPolicy)
{
if ($originPolicy === null) {
return array();
}
foreach ($originPolicy as $key => $value) {
if (in_array((string) $key, self::$deprecatedPolicyFields, true)) {
throw new \InvalidArgumentException("{$key} has deprecated");
}
if (!$strictPolicy || in_array((string) $key, self::$policyFields, true)) {
$policy[$key] = $value;
}
}
return $policy;
}
public function authorization($url, $body = null, $contentType = null)
{
$authorization = 'QBox ' . $this->signRequest($url, $body, $contentType);
return array('Authorization' => $authorization);
}
}
我是直接把这个文件放到了Home\Controller 下面,使用方便,直接new一下就Ok .2,sdk里面有一个function文件,这个文件里面有需要用到的函数,可以把这个function里面的函数复制到common下面的function.php里面,不然不能获取到uptoken。
3,以上两个准备好以后,就可以new一下,获取到uptoken 了。
public function uptoken(){
//七牛
$accessKey = '';
$secretKey = '';
$bucket = '';
// 初始化签权对象
$auth = new Auth($accessKey, $secretKey);
/* $policy = array(
'callbackUrl' => 'http://ph3515.duapp.com/index.php/Home/Guakao/callback',
'callbackBody' => '{"fname":"$(fname)", "fkey":"$(key)", "desc":"$(x:desc)", "uid":' . $uid . '}'
); */
$token = $auth->uploadToken($bucket);
$data=array('uptoken'=>$token);
$json=json_encode($data);
echo $json;
/* $auth = new Auth($this->accessKey, $this->secretKey);;
$bucket = $this->bucket; // 要上传的空间
$key = time() . '.jpg';//自定义的名字,如果不设置,就跟hash相同
$policy = array(
'returnUrl' => $this->returnUrl,
'returnBody'=> '{"key": $(key), "hash": $(etag), "w": $(imageInfo.width), "h": $(imageInfo.height)}'
);
$token = $auth->uploadToken($bucket, $key, 3600, $policy); // 生成上传 Token
$this->assign('token', $token);
$this->assign('key', $key); */
}
4,php+js,是一个不错的选择,这两个配合起来就非常的爽,真是青梅竹马,天生一对,地上一双。去七头牛的官方下载一个jssdk,然后依葫芦画瓢,我这里只说一下重点。要去下载一个plupload和一个bootstrap,然后放到public里面,便于引用。重要的操作函数,在main.js这个文件里。前端的html代码如下:
<div role="tabpanel" class="tab-pane fade in active" id="demo" aria-labelledby="demo-tab">
<div class="row" style="margin-top: 20px;">
<input type="hidden" id="domain" value="你的domain">
<input type="hidden" id="uptoken_url" value="你的uptoken后台url">
<ul class="tip col-md-12 text-mute">
<li>
<small>
你选择的分类是:{$title}
</small>
</li>
<li>
<small>请上传证书照片</small>
</li>
</ul>
<div class="col-md-12">
<div id="container">
<a class="btn btn-default btn-lg " id="pickfiles" href="#" >
<i class="glyphicon glyphicon-plus"></i>
<span>选择文件</span>
</a>
</div>
</div>
<div style="display:none" id="success" class="col-md-12">
<div class="alert-success">
队列全部文件处理完毕
</div>
</div>
<div class="col-md-12 ">
<table class="table table-striped table-hover text-left" style="margin-top:40px;display:none">
<thead>
<tr>
<th class="col-md-4">Filename</th>
<th class="col-md-2">Size</th>
<th class="col-md-6">Detail</th>
</tr>
</thead>
<tbody id="fsUploadProgress">
</tbody>
</table>
</div>
</div>
</div>
就说这么多了。关于回调的问题,我用的是ajax的方法,在main.js 里面,有一段代码,我贴出来。'FileUploaded': function(up, file, info) {
var progress = new FileProgress(file, 'fsUploadProgress');
progress.setComplete(up, info);
var domain = up.getOption('domain');
var res = $.parseJSON(info);
var sourceLink = domain + res.key; //获取上传成功后的文件的Url
$.post('你的回调url',{key:sourceLink});
},
然后在后台接受这个key,就是上传后的文件地址,还等什么呢,把它存入数据库吧。