如何在Angular JS中显示以字节数组形式接收的图像 [英] How to display Image received as byte array in Angular JS
问题描述
我有一个服务器端应用程序,它将返回一个图像.这些是响应头:
I have a server side application that will return an image. These are the response headers:
Content-Disposition: attachment; filename=8822a009-944e-43f4-999b-d297198d302a;1.0_low-res
Content-Length: 502343
Content-Type: image/png
Date: Mon, 03 Aug 2015 19:13:39 GMT
Server: Apache-Coyote/1.1
我需要显示图像.获取图像时,我使用angularJS $http
调用服务器并将结果放入范围中,但是我从未达到$http
的成功函数.从邮递员执行此呼叫将正常返回图像.我很好奇如何让Angular显示图像.
In angular, I need to display the image. When getting the image, I use the angularJS $http
to call the server and put the result in scope, but I never reach the success function of $http
. Executing this call from postman returns the image normally. I'm curious to how to get Angular to display the image.
这是我显示图像的方式:
This is how I display the image:
<img ng-src={{image}} />
以下是从服务器获取图像的调用:
Here is the call to get the image from the server:
$http.get(url, {responseType: "arraybuffer"})
.success(function(data) {
$scope.image= data;
}
)
推荐答案
我同意贝卢的回答,因为您应该在$http.get
返回的promise上使用.then
函数,而不是.success
函数. .但是,我想您的ng-src
引用仍然会有问题,因为您没有为其提供URL,而是为您的字节数组提供了引用.
I agree with Bellu's response in that you should be using the .then
function, rather than the .success
function on the promise returned from the $http.get
. However, I'd imagine you'll still have an issue with your ng-src
reference in that you are not supplying it with a URL, but instead a reference to your byte array.
要将您的ng-src
引用绑定到客户端的内存中保存的字节数组,您的绑定应采用以下形式:
To bind your ng-src
reference to a byte array held in memory on the client, your binding should take the following form:
<img ng-src="data:image/JPEG;base64,{{image}}">
修改
由于我从未明确提及它,因此上面的ng-src
绑定假定您的图像数据为base64格式.如果数组不是base64格式,则HarrisonA提供了以下方法来转换该数组.
Since I never mentioned it explicitly, the ng-src
binding above assumes that your image data is in base64 format. HarrisonA provided a method below to convert the array if it isn't already in base64 format.
这篇关于如何在Angular JS中显示以字节数组形式接收的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!