Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve image from database using Web API, then displaying it in angularJS

Seems like a straightforward issue, but how can you retrieve an image stored in a database, using Web API, then display it using Angular?

Here is an example Web API service which is correctly returning a JPG file (using 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;
    }

Then on the http client-side, I am using angular to retrieve the data. Data is definitely getting retrieved, but just not displayed.

    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;
}

And the html:

 <img ng-src="{{cameraPic}}" /> </div>
like image 844
Douglas Timms Avatar asked Nov 27 '25 22:11

Douglas Timms


1 Answers

Looking at your server side code, I think you can directly write like this:

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

Just make sure you are replacing ehConstants.incidenT_IDX with actual content.

like image 162
Shashank Agrawal Avatar answered Nov 29 '25 13:11

Shashank Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!