无法检索laravel 5中存储在公用文件夹中的文件

时间:2017-06-18 12:51:18

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

我需要存储上传到表单中的图像,将图像存储在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)的网址格式,但public/uploads/some_id/unique_name.png中有唯一名称。

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

1 个答案:

答案 0 :(得分:0)

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

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

然后你可以循环你的刀片并获得正确的路径。

它看起来像这样:

// 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();
相关问题