1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App\Service;
- use OSS\OssClient;
- class OssService
- {
- private $accessKeyId, $accessKeySecret, $endpoint, $bucket, $ossClient;
- public function __construct($bucket = '')
- {
- $this->accessKeyId = config('oss.OSS_ACCESS_ID');
- $this->accessKeySecret = config('oss.OSS_ACCESS_KEY');
- $this->endpoint = config('oss.OSS_ENDPOINT');
- $this->bucket = $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 = '', $uploadFileName = null)
- {
- $uploadFileName = $uploadFileName ?: uniqid('kx-') . '.' . $fileType;
- $ossClient = $this->ossClient->uploadFile(
- $this->bucket,
- $path . $uploadFileName,
- $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;
- }
- }
|