频道文章 技术学习 阿里云OSS支持

阿里云OSS支持

7
原创  

安装扩展包

# laravel >=9.0 
composer require alphasnow/aliyun-oss-laravel:^4.0
# laravel >=5.5 <9.0
composer require alphasnow/aliyun-oss-laravel:^3.0

阿里云oss配置

# /your project/config/filesystems.php 下的 disks节点添加一下配置节点
  'oss' => [            
              'driver' => 'oss',            
              'access_key_id' => 'your access key id',            
              'access_key_secret' => 'yor access key secret',            
              'bucket' => 'your bucket',            
              'endpoint' => 'your endpoint', // OSS 外网节点或自定义外部域名
              'debug' => false
        ],

自动上传到oss

# /your project/app/Providers/AppServiceProvider# 在public function boot(){}方法内添加以下内容
        //替换上传文件显示基础URL为阿里云地址
        \config([            
            "data.baseUrl" => \str("https://")->append(
                \config("filesystems.disks.oss.bucket", "")
            )->append(".")->append(
                \config("filesystems.disks.oss.endpoint", "")
            )->append(DIRECTORY_SEPARATOR)
        ]);        //监听文件上传成功事件
        Event::listen(\ModStart\Data\Event\DataUploadedEvent::class, function (\ModStart\Data\Event\DataUploadedEvent $event) {
            $model = (new \ModStart\Data\Repository\DatabaseDataRepository())->getDataById($event->dataId);            if ($model) {
                $targetDirOssPath = \str(\ModStart\Data\AbstractDataStorage::DATA)
                    ->append(DIRECTORY_SEPARATOR)
                    ->append($event->category)
                    ->append(DIRECTORY_SEPARATOR)
                    ->append($model["path"])
                    ->dirname()
                    ->toString();
                $localFilePath = public_path(
                    \str(\ModStart\Data\AbstractDataStorage::DATA)
                        ->append(DIRECTORY_SEPARATOR)
                        ->append($event->category)
                        ->append(DIRECTORY_SEPARATOR)
                        ->append($model["path"])
                        ->toString()
                );
                $uploadFileName = \str($localFilePath)->basename()->toString();
                $uploadFileOssPath = Storage::disk("oss")->putFileAs($targetDirOssPath, $localFilePath, $uploadFileName);                if (\str($uploadFileOssPath)->isNotEmpty()) {                    if (File::exists($localFilePath)) {
                        File::delete($localFilePath);
                    }
                }
            }
        });



更新:2026-01-14 15:24:53 © 著作权归作者所有
QQ
微信
客服