Bez popisu

OssServices.php 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. namespace App\Services;
  3. use OSS\OssClient;
  4. class OssServices
  5. {
  6. private $accessKeyId, $accessKeySecret, $endpoint, $bucket, $ossClient;
  7. public function __construct()
  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 = config('oss.OSS_TEST_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 = '/')
  24. {
  25. if ($path != '/') {
  26. $path = '/' . trim($path, '/') . '/';
  27. }
  28. $ossClient = $this->ossClient->uploadFile(
  29. $this->bucket,
  30. 'tbk' . $path . uniqid('kx-') . '.' . $fileType,
  31. $file
  32. );
  33. return $ossClient;
  34. }
  35. /**
  36. * 阿里云文件路径
  37. * @param $fileUrl [阿里云路径]
  38. * @return null|string
  39. */
  40. public function delete($fileUrl)
  41. {
  42. if (!isset(parse_url($fileUrl)['path'])) {
  43. return false;
  44. }
  45. $fileUrl = ltrim(parse_url($fileUrl)['path'], '/');
  46. $ossClient = $this->ossClient->deleteObject(
  47. $this->bucket,
  48. $fileUrl
  49. );
  50. return $ossClient;
  51. }
  52. /**
  53. * 检查文件是否存在
  54. * @param $fileUrl [阿里云路径]
  55. * @return bool
  56. */
  57. public function exist($fileUrl)
  58. {
  59. if (!isset(parse_url($fileUrl)['path'])) {
  60. return false;
  61. }
  62. $fileUrl = ltrim(parse_url($fileUrl)['path'], '/');
  63. $ossClient = $this->ossClient->doesObjectExist(
  64. $this->bucket,
  65. $fileUrl
  66. );
  67. return $ossClient;
  68. }
  69. /**
  70. * 批量上传到阿里云OSS
  71. * @param $fileType [文件类型]
  72. * @param $file [本地文件路径]
  73. * @param $path [存储阿里云路径]
  74. * @return null
  75. * @throws \OSS\Core\OssException
  76. */
  77. public function uploadImg($fileType, $file, $path = 'tbk')
  78. {
  79. if ($path != '/') {
  80. $path = '/' . trim($path, '/') . '/';
  81. }
  82. $filename = pathinfo($file,PATHINFO_BASENAME);
  83. $ossClient = $this->ossClient->uploadFile(
  84. $this->bucket,
  85. 'tbk'.$path.$filename,
  86. $file
  87. );
  88. return $ossClient;
  89. }
  90. }