本文介绍了Laravel:路由到存储文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现的目标是建立到存储文件夹的路由,以便即使它不在public目录下也可以访问它.

What I'm trying to achieve is to make a route to the storage folder so that I can access it even if it's not under the public directory.

例如,用户的化身位于app\storage\user\avatars\avatar.jpg中,我想建立一条路线,以便可以从http://localhost/user/avatars/avatar.jpg之类的地方访问这些图像.

For example, user's avatars are located in app\storage\user\avatars\avatar.jpg and I would like to make a route so that I can access those images from something like http://localhost/user/avatars/avatar.jpg.

我该如何实现?

推荐答案

首先,我建议将avatars文件夹移动到更可公开访问的位置.但是作为Laravel,您可以实现所需的任何功能.

Firstly, i would recommend moving the avatars folder to somewhere more publicly accessible. But as its Laravel, you can achieve whatever you want.

Route::get('user/avatars/{filename}', function($filename)
{
    $filePath = storage_path().'/user/avatars/'.$filename;

    if ( ! File::exists($filePath) or ( ! $mimeType = getImageContentType($filePath)))
    {
        return Response::make("File does not exist.", 404);
    }

    $fileContents = File::get($filePath);

    return Response::make($fileContents, 200, array('Content-Type' => $mimeType));
});

然后在某处添加此自定义帮助器功能:

Then somewhere add this custom helper function:

function getImageContentType($file)
{
    $mime = exif_imagetype($file);

    if ($mime === IMAGETYPE_JPEG)
        $contentType = 'image/jpeg';

    elseif ($mime === IMAGETYPE_GIF)
        $contentType = 'image/gif';

    else if ($mime === IMAGETYPE_PNG)
        $contentType = 'image/png';

    else
        $contentType = false;

    return $contentType;
}

值得注意的是,您提出的方法和解决方案存在安全问题.

It may be worth noting that there are security concerns with the method you are proposing and the solutions.

这篇关于Laravel:路由到存储文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 13:03