2016-08-03 68 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');

希望它可以帮助=)