QQ扫一扫联系
# laravel >=9.0 composer require alphasnow/aliyun-oss-laravel:^4.0 # laravel >=5.5 <9.0 composer require alphasnow/aliyun-oss-laravel:^3.0
# /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 ],
# /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);
}
}
}
});