123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- declare(strict_types=1);
- namespace App\Service;
- use Aws\S3\S3Client;
- use Hyperf\HttpServer\Contract\ResponseInterface;
- use function Hyperf\Support\env;
- use App\Tools\Result;
- use Hyperf\HttpMessage\Upload\UploadedFile;
- class MinioService
- {
- /**
- * @Inject
- * @var ResponseInterface
- */
- protected $response;
- /**
- * @Inject
- * @var \Hyperf\Config\ConfigInterface
- */
- protected $config;
- protected $s3Client;
- public function __construct()
- {
- $this->s3Client = new S3Client([
- 'version' => 'latest',
- 'region' => 'chinese',
- 'endpoint' => env("OSS_ENDPOINT"),
- 'use_path_style_endpoint' => true,
- 'credentials' => [
- 'key' => env("OSS_KEY"),
- 'secret' => env("OSS_SECRET"),
- ],
- ]);
- }
- /**
- * 没几把鸟用用来测试的
- * @return \Psr\Http\Message\ResponseInterface
- */
- public function listBuckets()
- {
- try {
- // 获取所有存储桶列表
- $result = $this->s3Client->listBuckets();
- // 提取存储桶名称
- $buckets = array_column($result['Buckets'], 'Name');
- return Result::success($buckets);
- } catch (\Aws\Exception\AwsException $e) {
- var_dump($e->getMessage());
- return Result::error("报错了");
- } catch (\Exception $e) {
- var_dump($e->getMessage());
- return Result::error("报错了");
- }
- }
- /**
- * 上传文件
- * @return array|string[]
- */
- public function uploadFile($data)
- {
- $acceptExt = ['png', 'jpg', 'jpeg', 'gif', 'xls', 'xlsx', 'pdf', 'doc', 'docx', 'ppt', 'zip', 'pptx', 'mp4', 'flv','rar','tar'];
- try {
- if (!in_array( $data['ext'], $acceptExt)) {
- return Result::error('文件名后缀不允许');
- }
- $fileName = time().mt_rand(1, 1000000) . '.' . $data['ext'];
- $finalPath = DIRECTORY_SEPARATOR.date('Ymd').DIRECTORY_SEPARATOR . $fileName;
- $key = $data['contentType'].$finalPath;
- var_dump("===key:",$key);
- $result = $this->s3Client->putObject([
- 'Bucket' => env("BUCKET"),
- 'Key' => $key,
- 'Body' => base64_decode($data['fileContent']),
- 'ACL' => 'public-read',
- 'ContentType' => $data['contentType'],
- ]);
- var_dump("返回值:",$result);
- $rep = [
- 'imgUrl'=>$result['ObjectURL'],
- 'id'=>uniqid(),
- 'src'=>$key,
- 'fileName'=>$fileName,
- 'fileType'=> $data['ext'],
- 'oldFileName'=>$data['fileName'],
- 'oldName'=>substr($data['fileName'], 0, -(strlen($data['ext'])+1)),
- ];
- return Result::success($rep);
- } catch (\Exception $e) {
- return Result::error($e->getMessage());
- }
- }
- }
|