企微短剧业务系统

OssService.php 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Service;
  3. use OSS\OssClient;
  4. class OssService
  5. {
  6. private $accessKeyId, $accessKeySecret, $endpoint, $bucket, $ossClient;
  7. public function __construct($bucket = '')
  8. {
  9. $this->accessKeyId = config('oss.OSS_ACCESS_ID');
  10. $this->accessKeySecret = config('oss.OSS_ACCESS_KEY');
  11. $this->endpoint = config('oss.OSS_ENDPOINT');
  12. $this->bucket = $bucket;
  13. $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
  14. }
  15. /**
  16. * 上传到阿里云OSS
  17. * @param $fileType [文件类型]
  18. * @param $file [本地文件路径]
  19. * @param $path [存储阿里云路径]
  20. * @return null
  21. * @throws \OSS\Core\OssException
  22. */
  23. public function upload($fileType, $file, $path = '', $uploadFileName = null)
  24. {
  25. $uploadFileName = $uploadFileName ?: uniqid('kx-') . '.' . $fileType;
  26. $ossClient = $this->ossClient->uploadFile(
  27. $this->bucket,
  28. $path . $uploadFileName,
  29. $file
  30. );
  31. return $ossClient;
  32. }
  33. /**
  34. * 阿里云文件路径
  35. * @param $fileUrl [阿里云路径]
  36. * @return null|string
  37. */
  38. public function delete($fileUrl)
  39. {
  40. if (!isset(parse_url($fileUrl)['path'])) {
  41. return false;
  42. }
  43. $fileUrl = ltrim(parse_url($fileUrl)['path'], '/');
  44. $ossClient = $this->ossClient->deleteObject(
  45. $this->bucket,
  46. $fileUrl
  47. );
  48. return $ossClient;
  49. }
  50. /**
  51. * 检查文件是否存在
  52. * @param $fileUrl [阿里云路径]
  53. * @return bool
  54. */
  55. public function exist($fileUrl)
  56. {
  57. if (!isset(parse_url($fileUrl)['path'])) {
  58. return false;
  59. }
  60. $fileUrl = ltrim(parse_url($fileUrl)['path'], '/');
  61. $ossClient = $this->ossClient->doesObjectExist(
  62. $this->bucket,
  63. $fileUrl
  64. );
  65. return $ossClient;
  66. }
  67. }