QiniuService.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services;
  12. use Qiniu\Auth;
  13. use Qiniu\Storage\UploadManager;
  14. /**
  15. * 七牛存储接口管理-服务类
  16. * @author laravel开发员
  17. * @since 2020/11/11
  18. * @package App\Services
  19. */
  20. class QiniuService extends BaseService
  21. {
  22. // 静态对象
  23. protected static $instance = null;
  24. protected $host = '';
  25. protected $accessKey = '';
  26. protected $secretKey = '';
  27. protected $bucket = '';
  28. public function __construct()
  29. {
  30. $this->accessKey = ConfigService::make()->getConfigByCode('qiniu_access_key');
  31. $this->secretKey = ConfigService::make()->getConfigByCode('qiniu_secret_key');
  32. $this->bucket = ConfigService::make()->getConfigByCode('qiniu_bucket','');
  33. $this->host = ConfigService::make()->getConfigByCode('qiniu_host','');
  34. }
  35. /**
  36. * 静态入口
  37. */
  38. public static function make(){
  39. if(!self::$instance){
  40. self::$instance = new static();
  41. }
  42. return self::$instance;
  43. }
  44. /**
  45. * 查询
  46. * @param $no 快递单号
  47. * @param string $phone // 手机号
  48. * @param string $code 快递公司编号
  49. * @return bool
  50. */
  51. public function upload($filename,$file)
  52. {
  53. // 配置参数
  54. if(empty($this->apiKey) || empty($this->apiCode) || empty($this->bucket) || empty($this->host)){
  55. $this->error = '接口参数未配置';
  56. return false;
  57. }
  58. // 初始化鉴权对象
  59. $auth = new Auth($this->accessKey, $this->secretKey);
  60. // 生成上传策略
  61. $policy = null;
  62. $uptoken = $auth->uploadToken($this->bucket, $filename, 3600, $policy);
  63. // 初始化 UploadManager 对象并进行文件上传
  64. $uploadMgr = new UploadManager();
  65. list($ret, $err) = $uploadMgr->putFile($uptoken, $filename, $file->getPathname());
  66. if ($err !== null) {
  67. $this->error = '图片上传失败:' . $err->getMessage();
  68. return false;
  69. } else {
  70. return $this->host . '/' . $filename;
  71. }
  72. }
  73. }