完成此操作的最直接方法是添加新磁盘。通过这种方式,您可以在不影响现有文件和 url 的情况下将新模式应用于图像,以及许多其他好处。
步骤1
将您的磁盘添加到config/filesystems.php:
'images' => [
'driver' => 'local',
'root' => storage_path('app/public/images'),
'url' => env('APP_URL') . '/images',
'visibility' => 'public',
],
以下是如何将文件上传从控制器保存到新磁盘的示例:
// storeAs: path, filename, disk
$request->file('image')->storeAs('/', 'x.jpg', 'images')
这就是您生成图像链接的方式,如下所示http://example.com/images/x.jpg
:
Storage::disk('images')->url('x.jpg')
第2步
以下是从新路径提供文件的三个不同选项(您只需选择一个):
选项1
在您的公共目录中创建一个符号链接。
ln -s /var/www/example.com/storage/app/public/images /var/www/example.com/public/images
这与 Laravel 用于默认公共磁盘(/storage
URL)的方法相同。
从 Laravel 7 开始,您可以修改config/filesystems.php
以管理其他符号链接:
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
public_path('images') => storage_path('app/public/images'),
],
选项 2
在你的 Laravel 应用程序中创建一个路由来提供图像:
Route::get('images/{file}', function ($file) {
return Storage::disk('images')->response($file);
// or to trigger downloads:
// return Storage::disk('images')->download($file);
});
此选项的缺点是它使用 PHP 进程为每个图像提供服务,而不是像选项 1 和 3 那样由网络服务器处理。
选项 3
在您的网络服务器中创建一个重写规则。
在 nginx 中,它可能看起来像这样:
location /images/ {
root /var/www/example.com/storage/app/public/;
}
在 Apache 中,您可以使用别名:
Alias "/images" "/var/www/example.com/storage/app/public/images"