轉自Thinkphp官方的一個代碼演示案例。
使用的TP3.1.X的框架,不支持命名空間,所以把api整合到一個文档裡了,省得引入不正確
<?php
class QiniuAction extends Action
{
public $accessKey = '******WqG8S6_d0z81ctXRe9q**********'; //請自行去七牛申請
public $secretKey = '*************Y6Hi7nsdaqsI**********'; //請自行去七牛申請
public $bucket = 'test12345'; //你的七牛管理後台的某個空間名
public $domain = 'http://xxxxxx.clouddn.com/'; //你的七牛管理後台的分配給你的域名,位於 空間設置->域名設置->七牛域名
public $returnUrl = 'http://yourdomain.com/index.php'; //上傳成功後的回調地址
public $QiniuAuth;
protected function _initialize()
{
parent::_initialize();
import('@.Common.Qiniu');
$this->QiniuAuth = new Auth($this->accessKey, $this->secretKey);
}
// 列表頁
public function index()
{
$auth = $this->QiniuAuth;
$bucketMgr = new BucketManager($auth);
$bucket = $this->bucket;
$prefix = '';
$marker = '';
$limit = 100; //顯示數量
list($iterms, $marker, $err) = $bucketMgr->listFiles($bucket, $prefix, $marker, $limit);
if ($err !== null) {
dump($err);
$this->error('發生錯誤,請聯繫管理員。');
} else {
foreach ($iterms as $key => $val) {
$expire = time() + 3600; //過期時間(秒)
$url = $this->domain . $val['key'] . '?e=' . $expire; //構造URL
$sign = $auth->sign($url); //進行簽名加密
$token = '&token=' . $sign; //組裝簽名得到的token
$val['url'] = $url . $token; //生成最終url
$iterms[$key] = $val;
}
$this->assign('list', $iterms);
}
$this->display();
}
//上傳(模板文档見附件)
public function add()
{
$auth = $this->QiniuAuth;
$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);
$this->display();
}
public function del()
{
$key = I('get.key');
if ($key !== '') {
$auth = $this->QiniuAuth;
$bucketMgr = new BucketManager($auth);
if ($err = $bucketMgr->delete($this->bucket, $key) == null) {
redirect($_SERVER['HTTP_REFERER']);
} else {
$this->error('刪除失敗');
}
} else {
redirect($_SERVER['HTTP_REFERER']);
}
}
}