从yii2中的rest api获取图像

时间:2017-06-19 06:23:18

标签: json rest yii2

我的网络服务中有代码来获取这样的数据

public function actionView($id){
    $model=Customer::find()->where(['id'=>$id])->andWhere(['not in','status','deleted'])->one();
    try {
        $response['success']=true;
        $response['code']=200;
        if (!$model) {
            throw new Exception("not found data", 404); 
        }
        $response['data']=$model;
    } catch (Exception $e) {
        $response['success']=false;
        $response['code']=$e->getCode();
        $response['data']=$e->getMessage();
    }
    return $response;
}

我从我的网络服务

获得了json
{
    "success": true,
    "code": 200,
    "data": {
        "id": 47,
        "name": "faza baru",
        "email": "baru@ashas.com",
        "address": "pekalongan",
        "created_at": "2017-06-15 14:44:42",
        "updated_at": "2017-06-15 14:52:38",
        "status": "active",
        "country": {
            "id": 1,
            "code": "INA",
            "name": "Indonesialan",
            "created_at": "2017-06-06 09:37:55",
            "updated_at": "2017-06-06 09:37:55"
        },
        "city": {
            "id": 1,
            "code": "JKT",
            "name": "jakarta",
            "country_id": 1,
            "created_at": "2017-06-06 10:10:50",
            "updated_at": "2017-06-06 10:10:50"
        },
        "image": "<img src=\"https://www.w3schools.com/css/img_fjords.jpg\">"
    }
}

在我的邮递员没有显示图像 enter image description here

但是我试图在http://jsonviewer.stack.hu/显示图片中查看json enter image description here

怎么能解决这个问题?以图像显示

1 个答案:

答案 0 :(得分:0)

返回二进制base64数据,如下所示:

return [
    ......
    'image'=>base64_encode($image)
];

在js中使用:

$('.img').html('<img src="data:image/png;base64,' + data.image + '" />');