123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- <?php
- namespace App\Services;
- use OSS\OssClient;
- class OssServices
- {
- private $accessKeyId, $accessKeySecret, $endpoint, $bucket, $ossClient;
- public function __construct()
- {
- $this->accessKeyId = config('oss.OSS_ACCESS_ID');
- $this->accessKeySecret = config('oss.OSS_ACCESS_KEY');
- $this->endpoint = config('oss.OSS_ENDPOINT');
- $this->bucket = config('oss.OSS_TEST_BUCKET');
- $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
- }
- /**
- * 上传到阿里云OSS
- * @param $fileType [文件类型]
- * @param $file [本地文件路径]
- * @param $path [存储阿里云路径]
- * @return null
- * @throws \OSS\Core\OssException
- */
- public function upload($fileType, $file, $path = '/')
- {
- if ($path != '/') {
- $path = '/' . trim($path, '/') . '/';
- }
- $ossClient = $this->ossClient->uploadFile(
- $this->bucket,
- 'tbk' . $path . uniqid('kx-') . '.' . $fileType,
- $file
- );
- return $ossClient;
- }
- /**
- * 阿里云文件路径
- * @param $fileUrl [阿里云路径]
- * @return null|string
- */
- public function delete($fileUrl)
- {
- if (!isset(parse_url($fileUrl)['path'])) {
- return false;
- }
- $fileUrl = ltrim(parse_url($fileUrl)['path'], '/');
- $ossClient = $this->ossClient->deleteObject(
- $this->bucket,
- $fileUrl
- );
- return $ossClient;
- }
- /**
- * 检查文件是否存在
- * @param $fileUrl [阿里云路径]
- * @return bool
- */
- public function exist($fileUrl)
- {
- if (!isset(parse_url($fileUrl)['path'])) {
- return false;
- }
- $fileUrl = ltrim(parse_url($fileUrl)['path'], '/');
- $ossClient = $this->ossClient->doesObjectExist(
- $this->bucket,
- $fileUrl
- );
- return $ossClient;
- }
- /**
- * 批量上传到阿里云OSS
- * @param $fileType [文件类型]
- * @param $file [本地文件路径]
- * @param $path [存储阿里云路径]
- * @return null
- * @throws \OSS\Core\OssException
- */
- public function uploadImg($fileType, $file, $path = 'tbk')
- {
- if ($path != '/') {
- $path = '/' . trim($path, '/') . '/';
- }
- $filename = pathinfo($file,PATHINFO_BASENAME);
- $ossClient = $this->ossClient->uploadFile(
- $this->bucket,
- 'tbk'.$path.$filename,
- $file
- );
- return $ossClient;
- }
- }
|