<?php
namespace app\common\library\storage\engine;
use think\Exception;
use think\Request;
/**
存儲引擎抽象類
Class server
@package app\common\library\storage\drivers
*/
abstract class Server
{
protected $file;
protected $error;
protected $fileName;
protected $fileInfo;
/**
* 構(gòu)造函數(shù)
* Server constructor.
* @throws Exception
*/
protected function __construct()
{
// 接收上傳的文件
$this->file = Request::instance()->file('iFile');
if (empty($this->file)) {
throw new Exception('未找到上傳文件的信息');
}
// 生成保存文件名
$this->fileName = $this->buildSaveName();
// 文件信息
$this->fileInfo = $this->file->getInfo();
}
/**
* 文件上傳
* @return mixed
*/
abstract protected function upload();
/**
* 返回上傳后文件路徑
* @return mixed
*/
abstract public function getFileName();
/**
* 返回文件信息
* @return mixed
*/
public function getFileInfo()
{
return $this->fileInfo;
}
/**
* 返回錯誤信息
* @return mixed
*/
public function getError()
{
return $this->error;
}
/**
* 生成保存文件名
*/
private function buildSaveName()
{
// 要上傳圖片的本地路徑
$realPath = $this->file->getRealPath();
// 擴(kuò)展名
$ext = pathinfo($this->file->getInfo('name'), PATHINFO_EXTENSION);
// 自動生成文件名
return date('YmdHis') . substr(md5($realPath), 0, 5)
. str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . '.' . $ext;
}
}
<?php
namespace app\common\library\storage\engine;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
/**
七牛云存儲引擎
Class Qiniu
@package app\common\library\storage\engine
*/
class Qiniu extends Server
{
private $config;
/**
* 構(gòu)造方法
* Qiniu constructor.
* @param $config
* @throws \think\Exception
*/
public function __construct($config)
{
parent::__construct();
$this->config = $config;
}
/**
* 執(zhí)行上傳
* @return bool|mixed
* @throws \Exception
*/
public function upload()
{
// 要上傳圖片的本地路徑
$realPath = $this->file->getRealPath();
// 構(gòu)建鑒權(quán)對象
$auth = new Auth($this->config['access_key'], $this->config['secret_key']);
// 要上傳的空間
$token = $auth->uploadToken($this->config['bucket']);
// 初始化 UploadManager 對象并進(jìn)行文件的上傳
$uploadMgr = new UploadManager();
// 調(diào)用 UploadManager 的 putFile 方法進(jìn)行文件的上傳
list($result, $error) = $uploadMgr->putFile($token, $this->fileName, $realPath);
if ($error !== null) {
$this->error = $error->message();
return false;
}
return true;
}
/**
* 返回文件路徑
* @return mixed
*/
public function getFileName()
{
return $this->fileName;
}
}