2017-06-18 193 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