2016-08-03 62 views
2

我的所有用戶上傳文件目錄:如何從Laravel的資源中獲取圖像?

/resources/app/uploads/ 

我試圖通過完整路徑來獲得圖像:

http://localhost/resources/app/uploads/e00bdaa62492a320b78b203e2980169c.jpg 

,但我得到的錯誤:

NotFoundHttpException in RouteCollection.php line 161: 

我怎樣才能得到圖像通過這條路?

現在我嘗試uplaod在目錄/公/上傳文件/根:

$destinationPath = public_path(sprintf("\\uploads\\%s\\", str_random(8))); 
$uploaded = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath())); 

它給我的錯誤:

Impossible to create the root directory 
+0

嘗試上傳..然後你應該能夠進行資產訪問()方法.. – Jaimin

+0

好了,如何在'存儲指定路徑公共目錄: :將()'? – Dev

+0

你可以在保存時使用public_path(),當檢索時使用asset()。 – Jaimin

回答

3

你可以試試這個在您的刀片文件。圖像文件夾位於公用文件夾公用文件夾中

<img src="{{URL::asset('/images/image_name.png')}}" /> 
13

你可以讓路由專爲顯示圖像。

例如:

Route::get('/resources/app/uploads/{filename}', function($filename){ 
    $path = resource_path() . '/app/uploads/' . $filename; 

    if(!File::exists($path)) { 
     return response()->json(['message' => 'Image not found.'], 404); 
    } 

    $file = File::get($path); 
    $type = File::mimeType($path); 

    $response = Response::make($file, 200); 
    $response->header("Content-Type", $type); 

    return $response; 
}); 

所以,現在你可以去localhost/resources/app/uploads/filename.png,它應該顯示圖像。

+0

謝謝,但如果我需要獲得唯一的路徑img? – Dev

+0

這在使用Dingo API時幫助了我很多。 – Logus

2

嘗試{{asset('path/to/your/image.jpg')}}如果你想從你的刀片把它

,如果你在你的控制器希望$url = asset('path/to/your/image.jpg');

希望它可以幫助=)