【问题标题】:Unable to retrieve files stored in public folder in laravel 5无法检索存储在 laravel 5 公用文件夹中的文件
【发布时间】:2017-06-18 12:51:18
【问题描述】:

我需要将上传的图片存储在表单中,将图片存储在public/uploads文件夹中并将文件名保存在数据库中,然后不需要显示上传的文件。

我成功,将文件上传到public/uploads文件夹,但它存储的问题是生成了一个唯一的名称,而我存储在db中的名称是原始名称。

....
$post_images->image_file_name = $image->getClientOriginalName();
Storage::disk('uploads')->put('prefix_'.$post_id, $image);
$post_images->save();

在视图中显示时,

<img src="{{url('/uploads')}}/prefix_{{$images->post_id}}/{{$images->image_file_name}}">

原始文件名(public/uploads/some_id/my_original_file_name.png)的 url 形式,但在 public/uploads/some_id/unique_name.png 中具有唯一名称。

如何获取上传文件的唯一名称并将其保存在数据库中? 或者任何其他方式来实现这一点?

【问题讨论】:

  • 如何创建唯一名称?请提供更多代码
  • @utdev 唯一的名字是由 laravel 创建的。当我们使用Storage::disk('uploads')-&gt;put(); 时,它会创建一个唯一的文件名并保存文件。

标签: php laravel file-upload laravel-5 laravel-filesystem


【解决方案1】:

您可以在您的数据库(图像表)中创建另一个包含唯一图像路径的列。

因此,在保存原始图像名称及其路径后,您可以添加另一个保存函数来将唯一图像名称(路径)保存到数据库中。

然后你可以遍历你的刀片并找到正确的路径。

它看起来像这样:

// get all images in your controller method and pass those to your view
public index()
{
    $images = DB::table('images') // here you have to put the table name, where your images are saved at
    return view('image.index', compact('images'))
}

在你看来:

// loop through all images and get the path name from your database
@foreach($images as $imageKey => $imageValue)
     <img src="{{ $imageValue->unique_path }}" />
@endforeach

编辑:

要保存唯一的图像名称,您必须这样做:

$image->fill(['unique_image' => $prefix.'_'.$post_id.'.png']); // unique_image is your db column name, if its a png
$image->save();

【讨论】:

  • 是的,我知道我可以将它添加到 ti db,如何获得唯一名称是我的问题?
  • 之后你可以遍历你的模型并获取路径名等待生病将它添加到我的答案中
  • 我可以循环并得到它。我知道。如何首先获取唯一的文件名以将其存储在数据库中?你在找我吗?
  • @Mann 好的,我更新了我的答案,如果您有任何问题,请尽管问:) 希望它对您有所帮助并且您理解它
  • 您提供的代码从 db 获取文件并在视图中显示它们。我需要如何在数据库中保存唯一的文件名,而不是从数据库中检索来显示它们。
猜你喜欢
  • 2021-12-14
  • 2021-09-08
  • 2021-04-27
  • 2016-05-27
  • 2018-09-10
  • 2023-02-25
  • 2018-07-08
  • 1970-01-01
  • 2015-07-08
相关资源
最近更新 更多