Qiniu.php 2.1 KB

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