在共享主机上显示laravel存储的图像

Tan*_*may 2 shared-hosting laravel blade laravel-5 laravel-blade

我已经在实时服务器上成功部署了第一个laravel应用程序。除了我无法显示正在上传到/myproject_src/storage/app/public/myfolder1文件夹中的图像外,其他一切看起来都很不错 。

这是我在HostGator上的文件夹层次结构:

/ myproject_src /

这是所有laravel源文件(公用文件夹除外)

/public_html/mydomain.com/

这是我在公共目录中的所有内容

我以以下方式将文件路径存储到数据库中:

public/myfolder1/FxEj1V1neYrc7CVUYjlcYZCUf4YnC84Z3cwaMjVX.png

此路径与已上传到storage / app / public / myfolder1 /此文件夹的图像关联,并且是通过store('public/myfolder1');laravel方法生成 的。

我应该怎么做才能在img标签中正确显示图像:

<img src="{{ how to point to the uploaded image here }}">
Run Code Online (Sandbox Code Playgroud)

imr*_*shu 7

好了,您可以使用创建符号链接

php artisan storage:link
Run Code Online (Sandbox Code Playgroud)

并使用访问文件

<img src="{{ asset('public/myfolder1/image.jpg') }}" />
Run Code Online (Sandbox Code Playgroud)

但是有时候,如果您在共享主机上,则无法创建符号链接。您想要保护某些访问控制逻辑后面的文件,可以选择一种特殊的途径来读取和提供图像。例如。

Route::get('storage/{filename}', function ($filename)
{
    $path = storage_path($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;
});
Run Code Online (Sandbox Code Playgroud)

现在,您可以像这样访问文件。

http://example.com/storage/public/myfolder1/image.jpg
<img src="{{ asset('storage/public/myfolder1/image.jpg') }} />
Run Code Online (Sandbox Code Playgroud)

注意:出于灵活性考虑,我建议不要在db中存储路径。请仅存储文件名,然后在代码中执行以下操作。

Route::get('storage/{filename}', function ($filename)
{
    // Add folder path here instead of storing in the database.
    $path = storage_path('public/myfolder1' . $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;
});
Run Code Online (Sandbox Code Playgroud)

并使用

http://example.com/storage/image.jpg
Run Code Online (Sandbox Code Playgroud)

希望有帮助:)