Alioss.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace addons\alioss;
  3. use OSS\Core\OssException;
  4. use OSS\OssClient;
  5. use think\Addons;
  6. use think\Loader;
  7. /**
  8. * 阿里云OSS上传插件
  9. */
  10. class Alioss extends Addons
  11. {
  12. /**
  13. * 插件安装方法
  14. * @return bool
  15. */
  16. public function install()
  17. {
  18. return true;
  19. }
  20. /**
  21. * 插件卸载方法
  22. * @return bool
  23. */
  24. public function uninstall()
  25. {
  26. return true;
  27. }
  28. /**
  29. * 添加命名空间
  30. */
  31. public function appInit()
  32. {
  33. if (!class_exists("\OSS\OssClient")) {
  34. //添加支付包的命名空间
  35. Loader::addNamespace('OSS', ADDON_PATH . 'alioss' . DS . 'library' . DS . 'OSS' . DS);
  36. }
  37. }
  38. /**
  39. * 加载配置
  40. */
  41. public function uploadConfigInit(&$upload)
  42. {
  43. $config = $this->getConfig();
  44. $data = ['deadline' => time() + $config['expire']];
  45. $signature = hash_hmac('sha1', json_encode($data), $config['accessKeySecret'], true);
  46. $multipart = [
  47. 'aliosstoken' => $config['accessKeyId'] . ':' . base64_encode($signature) . ':' . base64_encode(json_encode($data))
  48. ];
  49. $config['uploadurl'] = 'https://' . $config['bucket'] . '.' . $config['endpoint'];
  50. $upload = array_merge($upload, [
  51. 'cdnurl' => $config['cdnurl'],
  52. 'uploadurl' => $config['uploadmode'] == 'client' ? $config['uploadurl'] : addon_url('alioss/index/upload', [], false, true),
  53. 'uploadmode' => $config['uploadmode'],
  54. 'bucket' => $config['bucket'],
  55. 'maxsize' => $config['maxsize'],
  56. 'mimetype' => $config['mimetype'],
  57. 'savekey' => $config['savekey'],
  58. 'chunking' => (bool)($config['chunking'] ?? $upload['chunking']),
  59. 'chunksize' => (int)($config['chunksize'] ?? $upload['chunksize']),
  60. 'multipart' => $multipart,
  61. 'storage' => $this->getName(),
  62. 'multiple' => $config['multiple'] ? true : false,
  63. ]);
  64. }
  65. /**
  66. * 附件删除后
  67. */
  68. public function uploadDelete($attachment)
  69. {
  70. $config = $this->getConfig();
  71. if ($attachment['storage'] == 'alioss' && isset($config['syncdelete']) && $config['syncdelete']) {
  72. try {
  73. $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
  74. $ossClient->deleteObject($config['bucket'], ltrim($attachment->url, '/'));
  75. } catch (OssException $e) {
  76. return false;
  77. }
  78. //如果是服务端中转,还需要删除本地文件
  79. //if ($config['uploadmode'] == 'server') {
  80. // $filePath = ROOT_PATH . 'public' . str_replace('/', DS, $attachment->url);
  81. // if ($filePath) {
  82. // @unlink($filePath);
  83. // }
  84. //}
  85. }
  86. return true;
  87. }
  88. }