我把用户的头像上传到了Laravel存储器里。我如何访问它们并在视图中呈现它们?

服务器将所有请求指向/public,那么如果它们在/storage文件夹中,我如何显示它们?


当前回答

如果你是在windows上,你可以在cmd上运行这个命令:

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

来自: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html

其他回答

最好将所有私有图像和文档保存在存储目录中,然后您将完全控制文件ether,您可以允许特定类型的用户访问文件或限制。

创建一个route/docs并指向任意控制器方法:

public function docs() {

    //custom logic

    //check if user is logged in or user have permission to download this file etc

    return response()->download(
        storage_path('app/users/documents/4YPa0bl0L01ey2jO2CTVzlfuBcrNyHE2TV8xakPk.png'), 
        'filename.png',
        ['Content-Type' => 'image/png']
    );
}

当你点击localhost:8000/docs文件时,如果存在的话,文件将被下载。

根据上面的代码,文件必须在root/storage/app/users/documents目录下,这是在Laravel 5.4上测试的。

如果你是在windows上,你可以在cmd上运行这个命令:

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

来自: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html

首先,您需要使用artisan命令为存储目录创建一个符号链接

php artisan storage:link

然后在任何视图中,你都可以像这样通过url helper访问你的图像。

url('storage/avatars/image.png');

最好的方法是创建一个像@SlateEntropy这样的符号链接。为了帮助实现这一点,从5.3版本开始,Laravel包含了一个命令,这使得这非常容易做到:

php artisan storage:link

这为你创建了一个从public/storage到storage/app/public的符号链接,这就是它的全部内容。现在/storage/app/public中的任何文件都可以通过如下链接访问:

http://somedomain.com/storage/image.jpg

如果由于某种原因,您不能创建符号链接(也许您在共享主机上,等等),或者您想在某些访问控制逻辑后面保护一些文件,那么可以使用一个特殊的路由来读取和服务映像。举个例子,像这样一个简单的闭合路径:

Route::get('storage/{filename}', function ($filename)
{
    $path = storage_path('public/' . $filename);

    if (!File::exists($path)) {
        abort(404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

你现在可以访问你的文件,就像你有一个符号链接一样:

http://somedomain.com/storage/image.jpg

如果你正在使用干预图像库,你可以使用它内置的响应方法来让事情更简洁:

Route::get('storage/{filename}', function ($filename)
{
    return Image::make(storage_path('public/' . $filename))->response();
});

警告 请记住,手动提供文件会导致性能损失,因为您要经历整个Laravel请求生命周期才能读取和发送文件内容,这比让HTTP服务器处理要慢得多。

无站点名称

{{Storage::url($photoLink)}}

如果你想添加网站名称 附加在api JSON felids上的例子

 public function getPhotoFullLinkAttribute()
{
 Storage::url($this->attributes['avatar']) ;
}