123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- <?php
- namespace plugin\qiniu_kodo\service;
- use laytp\traits\Error;
- use Qiniu\Auth;
- use Qiniu\Storage\UploadManager;
- use think\facade\Config;
- /**
- * Class Kodo
- * @package plugin\qiniu\service
- */
- class Kodo
- {
- use Error;
- protected static $instance;
- /**
- * 单例
- * @return static
- */
- public static function instance()
- {
- if (is_null(self::$instance)) {
- self::$instance = new static();
- }
- return self::$instance;
- }
- /**
- * 上传文件
- * @param $localFileName
- * @param $saveFileName
- * @param $config
- * @return bool
- * @throws \Exception
- */
- public function upload($localFileName, $saveFileName, $config)
- {
- try {
- $accessKey = $config['accessKey'];
- if (!$accessKey) {
- $this->setError('上传失败,七牛云的accessKey为空,请先配置');
- return false;
- }
- $secretKey = $config['secretKey'];
- if (!$secretKey) {
- $this->setError('上传失败,七牛云的secretKey为空,请先配置');
- return false;
- }
- $bucket = $config['bucket'];
- if (!$bucket) {
- $this->setError('上传失败,七牛云的bucket为空,请先配置');
- return false;
- }
- $domain = $config['domain'];
- if (!$domain) {
- $this->setError('上传失败,七牛云的domain为空,请先配置');
- return false;
- }
- $client = new Auth($accessKey, $secretKey);
- $token = $client->uploadToken($bucket);
- $uploadMgr = new UploadManager();
- list($ret, $err) = $uploadMgr->putFile($token, $saveFileName, $localFileName);
- if ($err !== null) {
- $this->setError('上传失败,' . $err);
- return false;
- } else {
- return $domain . '/' . $saveFileName;
- }
- } catch (\Exception $e) {
- $this->setError('上传失败,' . $e->getMessage());
- return false;
- }
- }
- /**
- * 客户端获取上传凭证token,然后由客户端JS-SDK将文件上传到七牛云KODO
- * @param $config
- * @return bool
- */
- public function token($config){
- try {
- $accessKey = $config['accessKey'];
- if (!$accessKey) {
- $this->setError('上传失败,七牛云的accessKey为空,请先配置');
- return false;
- }
- $secretKey = $config['secretKey'];
- if (!$secretKey) {
- $this->setError('上传失败,七牛云的secretKey为空,请先配置');
- return false;
- }
- $bucket = $config['bucket'];
- if (!$bucket) {
- $this->setError('上传失败,七牛云的bucket为空,请先配置');
- return false;
- }
- $domain = $config['domain'];
- if (!$domain) {
- $this->setError('上传失败,七牛云的domain为空,请先配置');
- return false;
- }
- $client = new Auth($accessKey, $secretKey);
- $token = $client->uploadToken($bucket);
- if ($token) {
- return $token;
- } else {
- $this->setError('七牛云上传凭证Token获取失败');
- return false;
- }
- } catch (\Exception $e) {
- $this->setError($e->getMessage());
- return false;
- }
- }
- }
|