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

Displaying laravel stored images on shared hosting

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

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

/myproject_src/

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

/public_html/mydomain.com/

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

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

public/myfolder1/FxEj1V1neYrc7CVUYjlcYZCUf4YnC84Z3cwaMjVX.png

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

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

<img src="{{ how to point to the uploaded image here }}">

嗯,您可以使用

创建符号 link
php artisan storage:link

并使用

访问文件
<img src="{{ asset('public/myfolder1/image.jpg') }}" />

但有时如果您使用的是共享主机,则无法创建符号 link。您想要保护某些访问控制逻辑背后的某些文件,可以选择使用特殊路径来读取和提供图像。例如。

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;
});

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

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

注意: 为了灵活性,我建议不要在数据库中存储路径。请只存储文件名并在代码中执行以下操作。

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;
});

并使用

访问它
http://example.com/storage/image.jpg

希望对您有所帮助:)

这里的简单答案是 运行 php artisan storage:link 手动命令

首先,删除 public 文件夹中的存储文件夹 然后将此代码添加到 web.php 文件的顶部。

Artisan::call('storage:link');

希望对您有所帮助。

一种简单可行的方法可能是在您的共享主机 ssh 终端中 运行 php artisan storage:link。然后只需在 filesystem.php

中为 public 驱动程序更改 url
'disks' => [

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/public/storage',
            'visibility' => 'public',
        ],
    ]