我正在使用存储提供商将文件上传到机架空间,就像这样…
$logo = $request->file('logo');
$content = fopen($logo->getRealPath(), 'r+');
'Storage::disk('cdn')->put('logo.png', $content);
现在,我如何获得上面文件的url?我一直在API中寻找一种方法,这似乎是不可能的。
- http://laravel.com/api/5.0/Illuminate/Filesystem/FilesystemAdapter.html
- http://laravel.com/api/5.0/Illuminate/Filesystem/Filesystem.html
我通常将磁盘公共URL存储在config/filessystems.php文件中。例如:
'google' => [
'driver' => 's3',
'key' => env('STORAGE_GOOGLE_KEY'),
'secret' => env('STORAGE_GOOGLE_SECRET'),
'bucket' => env('STORAGE_GOOGLE_BUCKET'),
'base_url' => 'https://storage.googleapis.com',
'public_url' => env('STORAGE_GOOGLE_PUBLIC_URL'),
],
然后在我的模型中,我为包含文件名的字段定义了一个赋值器:
public function getAvatarAttribute($value)
{
// If avatar isn't a URL, generate it
if (filter_var($value, FILTER_VALIDATE_URL) !== FALSE) {
return $value;
} else {
$disk = config('filesystems.default');
return config('filesystems.disks.'.$disk.'.public_url').'/avatars/'.$value;
}
}
这允许我:
- 随时更改默认磁盘并立即将所有引用指向我的新磁盘
- 如果需要,将实际URL存储在数据库中。在我的情况下,化身可能来自OAuth或实际的文件上传,所以我需要兼顾这两者
这里的问题是FlySystem适配器的工作方式。
对于大多数操作,它只会返回一个布尔值,指示操作是否成功。即使是Laravel的FlySystem包装器也不跟踪路径,因此解决方法是在成功上传后自己构建路径。
通过使用文件系统配置,我们可以得到这样的东西:
$cdn_url = config('filesystems.disks.cdn.container').'/logo.png';
你明白了。
在最近的Laravel版本中,您可以自定义存储URL
https://laravel.com/docs/8.x/filesystem#url-主机定制
URL主机自定义
如果要为使用生成的文件URL预先定义主机在Storage facade中,您可以向磁盘的配置阵列:
'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ],
例如'url' => 'https://cdn.example.com',
,或者只将其添加到.env文件中(s3的默认值为AWS_URL)