如何从 Laravel 的资源中获取图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38736717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get image from resources in Laravel?
提问by Dev
I upload all user files to directory:
我将所有用户文件上传到目录:
/resources/app/uploads/
I try to get image by full path:
我尝试通过完整路径获取图像:
http://localhost/resources/app/uploads/e00bdaa62492a320b78b203e2980169c.jpg
But I get error:
但我得到错误:
NotFoundHttpException in RouteCollection.php line 161:
How can I get image by this path?
如何通过此路径获取图像?
Now I try to uplaod file in directory /public/uploads/ in the root:
现在我尝试上传根目录 /public/uploads/ 中的文件:
$destinationPath = public_path(sprintf("\uploads\%s\", str_random(8)));
$uploaded = Storage::put($destinationPath. $fileName, file_get_contents($file->getRealPath()));
It gives me error:
它给了我错误:
Impossible to create the root directory
回答by Alfonz
You can make a route specifically for displaying images.
您可以制作专门用于显示图像的路线。
For example:
例如:
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;
});
So now you can go to localhost/resources/app/uploads/filename.png
and it should display the image.
所以现在你可以去localhost/resources/app/uploads/filename.png
它应该显示图像。
回答by Ronald
You may try this on your blade file. The images folder is located at the public folder
你可以在你的刀片文件上试试这个。图像文件夹位于公用文件夹
<img src="{{URL::asset('/images/image_name.png')}}" />
For later versions of Laravel (5.7 above):
对于更高版本的 Laravel(5.7 以上):
<img src = "{{ asset('/images/image_name.png') }}" />
回答by Han Lim
Try {{asset('path/to/your/image.jpg')}}
if you want to call it from your blade
{{asset('path/to/your/image.jpg')}}
如果您想从刀片中调用它,请尝试
or
或者
$url = asset('path/to/your/image.jpg');
if you want it in your controller.
$url = asset('path/to/your/image.jpg');
如果你想在你的控制器中使用它。
Hope it helps =)
希望它有帮助 =)