【问题标题】:How to access storage file using database query in LARAVEL如何在 LARAVEL 中使用数据库查询访问存储文件
【发布时间】:2020-02-06 06:57:28
【问题描述】:

我正在使用 laravel 项目并遇到问题。 我创建了一个名为“Product”的数据库模型,它有一个名为“product_image”的字段,它的数据类型是字符串。

public function up()
    {
        Schema::create('Products', function (Blueprint $table) {
            $table->string('product_image')->nullable();
            $table->timestamps();
        });
    }

通过使用控制器,我确实启用了上传产品图像和产品模型,能够获取该文件的活动名称及其扩展名,即使我能够在 storage/app/example.jpg 上找到该上传的文件。

$file = $request->file('product_image');
        $filename = 'product_image-' . time() . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('product-image', $filename);
        $product->product_image = $path ;

但是当我在我的刀片模板上运行 @foreach 循环并尝试通过它获取图像时。

@foreach ($products as $p)
<tr>
<td>{{$p->product_title}}</td>
<td><img src="/storage/app/product-image/{{$p->product_image}}" alt="" style="height:80px; width:80px"/></td>
@endforeach

我什么都没有创建,图像字段仍然显示没有原始图像:( enter image description here

我发现了问题,但不知道解决方案,迷失在黑暗中。 实际问题在,&lt;img src="/storage/app/product-image/{{$p->product_image}}" alt="" style="height:80px; width:80px"/&gt;

因为它没有为该图像创建 url。

我的问题是,我们如何使用 for 循环为该特定图像提供 URL,这将能够从 storage/app/example 目录中找到该图像。 提前致谢。

【问题讨论】:

    标签: php database laravel image url


    【解决方案1】:

    您是否尝试过使用 artisan 命令创建指向公共文件的符号链接,如描述 here

    运行php artisan storage:link

    在你的 config/filesystems.php 变成这样的东西:

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

    然后在刀片模板中像这样访问您的文件:

    <img src="{{ asset('product_image/'. $p->product_image) }}" alt="" style="height:80px; width:80px"/>
    

    【讨论】:

      【解决方案2】:

      您是否可以在浏览器中访问图片,例如 - http://urdomain.com/storage/app/product-image/example.jpg

      在您的问题中,您提到了 storage/app/example.jpg,但在您的模板中访问时,您将其称为 storage/app/product-image/example.jpg。路径会有问题吗?

      您的循环看起来不错。国际海事组织。

      【讨论】:

      • 看路径,没问题。
      【解决方案3】:

      另外,如果你使用 Vagrant 或 Laradock,你应该在你的工作空间中运行你的命令php artisan storage:link,否则它将无法工作,并且在你的浏览器中访问它时会导致 404。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-30
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        相关资源
        最近更新 更多