本文參考這篇文章:https://www.xm4021.com/article/9.html,并做了部分修改和補(bǔ)充,感謝原作者的分享!
composer安裝七牛SDK
composer require qiniu/php-sdk
config文件保存七牛云配置信息
//七牛云空間配置
'qiniu' => [
'AccessKey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'SecretKey' => 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
'bucket' => 'zzzzz',
'domain' => 'demo.domain.net/'
]
創(chuàng)建Qiniu Model,實(shí)現(xiàn)上傳功能
<?php
/**
* Created by PhpStorm.
* User: zgcli
* Date: 2019/2/12
* Time: 16:32
*/
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;
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 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' => $error, 'data' => $this->SecretKey];
} else {
return ['errNo' => 0, 'data' => ['bucket' => $this->bucket, 'key' => $key, 'url' => config('qiniu.domain').$key]];
}
}
/**
* 獲取私有空間或使用了原圖保護(hù)功能的圖片文件地址
* @param string $url 格式:http://domain/key[文件名]?e=時(shí)間戳
* @return string 可訪問的url地址:http://domain/key[文件名]?e=時(shí)間戳&token='token'
*/
public function getSignedUrl($url)
{
$signedUrl = $this->auth->privateDownloadUrl($url);
//該url地址需要驗(yàn)證是否可訪問。
return $signedUrl;
}
}
測試上傳功能
Controller:
public function test()
{
if ($this->request->isPost()) {
$qiniu = new \app\admin\model\Qiniu();
$data = $qiniu->upload('imgFile');
var_dump($data);
}
return $this->view->fetch();
}
View:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試七牛云上傳</title>
</head>
<body>
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="imgFile">
<input type="submit">
</form>
</body>
</html>