Aliyun.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. <?php
  2. namespace app\common\service\storage\engine;
  3. use OSS\OssClient;
  4. use OSS\Core\OssException;
  5. /**
  6. * 阿里云存储引擎 (OSS)
  7. * Class Qiniu
  8. * @package app\common\library\storage\engine
  9. */
  10. class Aliyun extends Server
  11. {
  12. private $config;
  13. /**
  14. * 构造方法
  15. * Aliyun constructor.
  16. * @param $config
  17. */
  18. public function __construct($config)
  19. {
  20. parent::__construct();
  21. $this->config = $config;
  22. }
  23. /**
  24. * 执行上传
  25. * @param $save_dir (保存路径)
  26. * @return bool|mixed
  27. */
  28. public function upload($save_dir)
  29. {
  30. try {
  31. $ossClient = new OssClient(
  32. $this->config['access_key'],
  33. $this->config['secret_key'],
  34. $this->config['domain'],
  35. true
  36. );
  37. $ossClient->uploadFile(
  38. $this->config['bucket'],
  39. $save_dir . '/' . $this->fileName,
  40. $this->getRealPath()
  41. );
  42. } catch (OssException $e) {
  43. $this->error = $e->getMessage();
  44. return false;
  45. }
  46. return true;
  47. }
  48. /**
  49. * Notes: 抓取远程资源
  50. * @param $url
  51. * @param null $key
  52. * @return mixed|void
  53. * @author 张无忌(2021/3/2 14:36)
  54. */
  55. public function fetch($url, $key = null)
  56. {
  57. try {
  58. $ossClient = new OssClient(
  59. $this->config['access_key'],
  60. $this->config['secret_key'],
  61. $this->config['domain'],
  62. true
  63. );
  64. // 使用curl获取$url
  65. $ch = curl_init();
  66. curl_setopt($ch, CURLOPT_URL, $url);
  67. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  68. curl_setopt($ch, CURLOPT_HEADER, 0);
  69. $content = curl_exec($ch);
  70. curl_close($ch);
  71. $ossClient->putObject(
  72. $this->config['bucket'],
  73. $key,
  74. $content
  75. );
  76. } catch (OssException $e) {
  77. $this->error = $e->getMessage();
  78. return false;
  79. }
  80. return true;
  81. }
  82. /**
  83. * 删除文件
  84. * @param $fileName
  85. * @return bool|mixed
  86. */
  87. public function delete($fileName)
  88. {
  89. try {
  90. $ossClient = new OssClient(
  91. $this->config['access_key'],
  92. $this->config['secret_key'],
  93. $this->config['domain'],
  94. true
  95. );
  96. $ossClient->deleteObject($this->config['bucket'], $fileName);
  97. } catch (OssException $e) {
  98. $this->error = $e->getMessage();
  99. return false;
  100. }
  101. return true;
  102. }
  103. /**
  104. * 返回文件路径
  105. * @return mixed
  106. */
  107. public function getFileName()
  108. {
  109. return $this->fileName;
  110. }
  111. }