66 lines
1.8 KiB
PHP
66 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace app\utils;
|
|
|
|
use app\constant\ResponseCode;
|
|
use Qiniu\Auth;
|
|
use Qiniu\Storage\UploadManager;
|
|
use think\Exception;
|
|
|
|
class QiniuUtils
|
|
{
|
|
|
|
|
|
/**
|
|
* @desc 上传到七牛云
|
|
* @param $filePath
|
|
* @return array
|
|
* @throws \Exception
|
|
*/
|
|
public static function upload($filePath = '')
|
|
{
|
|
|
|
try {
|
|
if(!file_exists($filePath)){
|
|
throw new Exception('文件不存在');
|
|
}
|
|
// 需要填写你的 Access Key 和 Secret Key
|
|
$accessKey = getenv('QI_NIU_ACCESS_KEY');
|
|
$secretKey = getenv('QI_NIU_SECRET_KEY');
|
|
$bucket = getenv('QI_NIU_BUCKET');
|
|
// 构建鉴权对象
|
|
$auth = new Auth($accessKey, $secretKey);
|
|
// 生成上传 Token
|
|
$token = $auth->uploadToken($bucket);
|
|
// 上传到存储后保存的文件名
|
|
$filename = pathinfo($filePath, PATHINFO_FILENAME);
|
|
|
|
$key = getenv('APP_NAME') .'/' . date('Ymd') . '/' . $filename . '.' . pathinfo($filePath, PATHINFO_EXTENSION);
|
|
|
|
// 初始化 UploadManager 对象并进行文件的上传。
|
|
$uploadMgr = new UploadManager();
|
|
// 调用 UploadManager 的 putFile 方法进行文件的上传。
|
|
list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath, null, 'application/octet-stream', true, null, 'v2');
|
|
|
|
if ($err !== null) {
|
|
throw new Exception($err->getResponse()->error);
|
|
}
|
|
$qiniu_url = getenv('QI_NIU_URL') . '/' . $ret['key'];
|
|
|
|
return [
|
|
'code' => ResponseCode::SUCCESS,
|
|
'data' => $qiniu_url,
|
|
];
|
|
|
|
}catch (Exception $e){
|
|
return [
|
|
'code' => ResponseCode::FAIL,
|
|
'msg' => $e->getMessage()
|
|
];
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
} |