Вопрос

I have a html page that looks like so:

<div ng-controller="DocumentCtrl">
    <img ng-src="data:image/tiff;base64,{{image}}" />
</div>

My Angular controller looks like this:

angular.controller('DocumentCtrl', ['$scope', '$http', function ($scope, $http) {

    $http.get('/api/Image').
        then(function (response) {
            $scope.image = response.data;
        });
}]);

And my ApiController GET like this:

public HttpResponseMessage Get()
{
    var file = HttpContext.Current.Server.MapPath("~/Images/docs/example.TIF");

    var stream = new FileStream(file, FileMode.Open);
    var content = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StreamContent(stream)
    };

    content.Content.Headers.ContentType = new MediaTypeHeaderValue("image/tiff");
    return content;
}

Inspecting the element in Chrome gives me this:

enter image description here

Now the data is binding to the UI correctly, but it always shows as a broken image link icon. I've tried various things, like changing the data type to image/* and using application/octet as the Content-Type, but nothing seems to make a difference.

Also, if I inspect the request with Fiddler and look at the ImageView of the response content, the image shows up there as I expect, so that portion of the process seems to be working correctly.

Is there something obvious I'm missing?

Thanks.

Это было полезно?

Решение

It appears your server does not render the image base64 encoded (from what I can see), if you base64 encode the image before sending it back then it should be fine.

Take a look at the below fiddle, the same request is used however I base64 encode the response on the 2nd image before assigning it to the scope (used the technique provided by Getting BLOB data from XHR request).

http://jsfiddle.net/kW4aV/2/

$http.get('http://lorempixel.com/50/50/', {responseType: "arraybuffer"}).success(function (resp) {
    $scope.image = resp;

    // Prep the response for Base64 encoding
    var uInt8Array = new Uint8Array(resp);
    var i = uInt8Array.length;
    var binaryString = new Array(i);
    while (i--)
    {
        binaryString[i] = String.fromCharCode(uInt8Array[i]);
    }
    var data = binaryString.join('');

    // Base64 encoded image and assign it to the scope
    $scope.image2 = window.btoa(data);
});

Note: that the fiddle will only work in Chrome and I do not suggest doing base64 encoding client side, best to do it on the server.

Другие советы

http://plnkr.co/edit/fa3owvnzZLBa72pDCeB5?p=preview

I created a plunker showing a working example:

<body ng-app="app" ng-controller="MainCtrl">

  <img ng-src="data:image/png;base64,{{image}}"  />

</body>

and

$scope.image = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top