2017-06-18 199 views
0

我需要存储的形式上传的图像,图像存储在public/uploads文件夹,并在数据库中保存的文件名,然后需要T查看上传的文件检索存储的公共文件夹中的文件。无法在laravel 5

我成功地将文件上传到public/uploads文件夹,但它存储的问题与生成的唯一名称存储在一起,并且我存储在数据库中的名称是原始名称。

.... 
$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}}"> 

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

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

+0

你如何创建联合国ique的名字?请提供更多的代码请致电 – utdev

+0

@utdev这个独特的名字是由laravel创建的。当我们使用'Storage :: disk('uploads') - > put();'它创建一个唯一的文件名并保存文件。 – Mann

回答

0

你可以在数据库中创建(图像表)的另一列其中包含了独特的图像路径。

所以保存原始imagename其路径后,你可以添加另一个保存功能以独特的图像名称(路径)保存到数据库中。

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

这将是这个样子,那么:

// 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(); 
+0

是的,我知道我可以添加它分贝,如何获得唯一的名称是我的问题? – Mann

+0

然后你可以遍历你的模型,并得到路径名等待虐待添加到我的答案 – utdev

+0

我可以循环和得到它。我知道。如何首先获取唯一的文件名来存储它的数据库?你在找我吗? – Mann