Laravel API 从带有数据库数据的公共文件夹返回图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39037461/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:20:23  来源:igfitidea点击:

Laravel API return image from public folder with database data

apilaravel

提问by Muhammad Anwar Shamim

I want to return image with data.

我想用数据返回图像。

$ads = DB::table('ads')->whereRaw('category_id=' .$id)->orderBy('id', 'desc')->get();

$filename = public_path().'/uploads/images/'.$ads->ad_image;
$filename = (file_get_contents($filename));
$image = Array('image'=>json_encode(base64_encode($filename)));
$ads[0]->image = $image;

return $ads; 

回答by jaysingkar

Assuming you want to show the images to the user on the page stored in laravel's storage directory, You can do the following implementation:

假设你想在laravel的存储目录中存储的页面上向用户展示图像,你可以做以下实现:

Create a controller to fetch and return the image as a response.

创建一个控制器来获取和返回图像作为响应。

<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
Use DB;


class PhotoController extends Controller
{
    public function image($fileName){
        $path = public_path().'/uploads/images/'.$fileName;
        return Response::download($path);        
    }
}

Add the Route to handle the image request

添加Route来处理图片请求

Route::get('image/{filename}',PhotoController @image);

Now, to access the image , lets say in image tag

现在,要访问图像,让我们在图像标签中说

<img src="image/abc.jpg">

PS:This method of serving images will have little overhead with respect to direct link of image...
In case, your images are public, you can simply create symbolic link of the directory where you have stored the images into the public directory.

PS:这种提供图像的方法对于图像的直接链接几乎没有开销......
如果您的图像是公开的,您可以简单地创建将图像存储到公共目录的目录的符号链接。

回答by Prakash Poudel

$filename = asset('/uploads/images/'.$ads->ad_image);

$filename = asset('/uploads/images/'.$ads->ad_image);