Qiniu.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. *
  4. * @copyright ©2020 点小铺
  5. * @author hanj
  6. * @link: https://dyuit.com
  7. * Created by VSCode
  8. */
  9. namespace app\common\library\storage\engine;
  10. use Qiniu\Auth;
  11. use Qiniu\Storage\UploadManager;
  12. use Qiniu\Storage\BucketManager;
  13. /**
  14. * 七牛云存储引擎
  15. * Class Qiniu
  16. * @package app\common\library\storage\engine
  17. */
  18. class Qiniu extends Server
  19. {
  20. private $config;
  21. /**
  22. * 构造方法
  23. * Qiniu constructor.
  24. * @param $config
  25. */
  26. public function __construct($config)
  27. {
  28. parent::__construct();
  29. $this->config = $config;
  30. }
  31. /**
  32. * 执行上传
  33. * @return bool|mixed
  34. * @throws \Exception
  35. */
  36. public function upload()
  37. {
  38. // 要上传图片的本地路径
  39. $realPath = $this->getRealPath();
  40. // 构建鉴权对象
  41. $auth = new Auth($this->config['access_key'], $this->config['secret_key']);
  42. // 要上传的空间
  43. $token = $auth->uploadToken($this->config['bucket']);
  44. // 初始化 UploadManager 对象并进行文件的上传
  45. $uploadMgr = new UploadManager();
  46. // 调用 UploadManager 的 putFile 方法进行文件的上传
  47. list(, $error) = $uploadMgr->putFile($token, $this->fileName, $realPath);
  48. /* @var $error \Qiniu\Http\Error */
  49. if ($error !== null) {
  50. $this->error = $error->message();
  51. return false;
  52. }
  53. return true;
  54. }
  55. /**
  56. * 删除文件
  57. * @param $fileName
  58. * @return bool|mixed
  59. */
  60. public function delete($fileName)
  61. {
  62. // 构建鉴权对象
  63. $auth = new Auth($this->config['access_key'], $this->config['secret_key']);
  64. // 初始化 UploadManager 对象并进行文件的上传
  65. $bucketMgr = new BucketManager($auth);
  66. /* @var $error \Qiniu\Http\Error */
  67. $error = $bucketMgr->delete($this->config['bucket'], $fileName);
  68. if ($error !== null) {
  69. $this->error = $error->message();
  70. return false;
  71. }
  72. return true;
  73. }
  74. /**
  75. * 返回文件路径
  76. * @return mixed
  77. */
  78. public function getFileName()
  79. {
  80. return $this->fileName;
  81. }
  82. }