问题的简短回答
这样做是否可以被视为良好的实践?或者我应该只是将图片保存在公共文件夹中?这样做会导致性能问题吗?
这不是建议的做法,因为您需要读取文件并重新生成它,这将花费处理时间并加载服务器,但这取决于请求数量、图像大小等。我使用此方法来保护图像/文件免受公众访问,因此只有经过身份验证的成员才能访问图像/文件,就像在这个answer中一样。再次取决于文件大小、请求数量和服务器规格,我已经使用了一段时间,并且性能没有任何问题,它运行得很好(我的服务器是512MB内存、1核处理器、20GB SSD硬盘VPS解决方案)。您可以试用一段时间并查看效果。
符号链接解决方案
也可以创建符号链接,例如
ln -s /pathof/laravel/storage/profile_pictures /pathof/laravel/public/profile
This solution won't affect performance, but you need to document the solution in your internal documentation, in case you move your setup to new provider or in case you need to re-link to the storage folder.
But if you still wish to have the full solution for returning image from storage folder, first of all we need to install Intervention Image for Laravel, I am not sure if this done already or not. If you have installed it, continue here, but if not, follow the last part of this answer and then continue with Laravel solution.
Laravel solution:
As mentioned, we assume your intervention works. First of all, you need to create a route that will forward all image request access to our controller.
Create Route.
Route::get('profile/{person}', 'ImagesController@profilePicture');
创建路由后,我们需要创建一个控制器来处理来自路由的图像请求。
创建ImagesController
从命令行输入:
php artisan make:controller ImagesController
而你的控制器应该长成这样。
class ImagesController extends Controller {
public function profilePicture($person, $size = 40)
{
$storagePath = storage_path('/profile_pictures/' . $person . '/profile_' . $size . '.jpg');
return Image::make($storagePath)->response();
}
}
编辑
对于使用 Laravel 5.2 及以上版本的用户。Laravel 引入了新的、更好的方式来 服务文件,这种方式的开销较小(不像答案中提到的那样会重新生成文件):
File Responses
The file method can be used to display a file, such as an image or
PDF, directly in the user's browser instead of initiating a download.
This method accepts the path to the file as its first argument and an
array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
记得添加
use Intervention\Image\Facades\Image;
在你的ImagesController
类中
最后确保你已经创建了包含测试图片的文件夹结构。
storage/profile_pictures/person/profile_40.jpg
现在,如果您在浏览器中编写
http://laravelLocalhostUrl/profile/person
它将显示您的图像,我自己制作并测试过。
注意:我已经尽最大努力使文件夹反映您的问题,但您可以轻松修改以适合您想要的方式。
安装Intervention(如果您已经安装了它,请跳过此部分)
按照以下指南:http://image.intervention.io/getting_started/installation
简要概述:php composer require intervention/image
并在您的config/app
中的$providers数组中添加此软件包的服务提供者。
Intervention\Image\ImageServiceProvider::class
将此包的门面添加到$aliases数组中。
'Image' => Intervention\Image\Facades\Image::class
这个解决方案的灵感来自于 这个答案,但那个是一般情况下用身份验证保护图像的方法,而这个 答案。