使用Web API从数据库中检索图像,然后在angularJS中显示它

时间:2015-12-28 08:24:33

标签: javascript angularjs asp.net-web-api

看起来像一个简单的问题,但是如何使用Web API检索存储在数据库中的图像,然后使用Angular显示它?

以下示例Web API服务正确返回JPG文件(使用HttpResponseMessage):

    public HttpResponseMessage GetIncidentImages(Guid IncidentIDX) {
        var response = new HttpResponseMessage();

        List<T_EM_INCIDENT_ATTACH> att = db_Layer.GetT_EM_INCIDENT_ATTACH_byIncidentIDX(IncidentIDX);
        if (att != null)
        {
            if (att.Count > 0)
            {
                var pictureBytes = att[0].ATTACH_CONTENT;  //ATTACH_CONTENT is a byte array

                if (pictureBytes == null)
                    response.StatusCode = HttpStatusCode.NotFound;
                else
                {
                    response.Content = new ByteArrayContent(pictureBytes);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                }
            }
            else
                response.StatusCode = HttpStatusCode.NotFound;
        }

        return response;
    }

然后在http客户端,我使用angular来检索数据。数据肯定会被检索,但只是没有显示。

    dbManagerService.syncIncidentAttach(ehConstants.incidenT_IDX).then(function (res) {
        console.log("return", res);

        $scope.cameraPic = res;
    });

function _syncIncidentAttach(incIDX) {
    var deferred = $q.defer();

    $http.get($rootScope.serverBaseUrl + 'api/incident/GetIncidentImages?IncidentIDX=' + incIDX, { responseType: "blob" })
    .success(function (res, status, headers, config) {
        // encode data to base 64 url
        fr = new FileReader();
        fr.onload = function () {
            // this variable holds your base64 image data URI (string)
            // use readAsBinary() or readAsBinaryString() below to obtain other data types
            console.log(fr.result);
        };
        fr.readAsDataURL(res);

        deferred.resolve(fr);
    })
    .error(function(data, status, headers, config) {
        conole.log('error getting image');
    });

    return deferred.promise;
}

和html:

 <img ng-src="{{cameraPic}}" /> </div>

2 个答案:

答案 0 :(得分:1)

查看服务器端代码,我认为你可以直接写这样:

<img ng-src="{{serverBaseUrl}}api/incident/GetIncidentImages?IncidentIDX={{ehConstants.incidenT_IDX}}" />

确保使用实际内容替换ehConstants.incidenT_IDX

答案 1 :(得分:0)

this answer中所述,您也可以执行类似

的操作
<img ng-src="{{'data:image/png;base64,' + main.user.imageData}}">