gpt4 book ai didi

javascript - 如何使用数据 URI 将从 ApiController 检索到的内容绑定(bind)到 Angular 元素?

转载 作者:行者123 更新时间:2023-11-29 18:15:52 25 4
gpt4 key购买 nike

我有一个如下所示的 html 页面:

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

我的 Angular Controller 看起来像这样:

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

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

我的 ApiController GET 是这样的:

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

检查 Chrome 中的元素给我这个:

enter image description here

现在数据已正确绑定(bind)到 UI,但它始终显示为损坏的图像链接图标。我尝试了各种方法,例如将数据类型更改为 image/* 并使用 application/octet 作为 Content-Type,但似乎没有什么不同。

此外,如果我使用 Fiddler 检查请求并查看响应内容的 ImageView,图像会按我的预期显示在那里,因此该过程的这一部分似乎工作正常。

我是否遗漏了一些明显的东西?

谢谢。

最佳答案

看起来你的服务器没有呈现 base64 编码的图像(据我所知),如果你在发送回图像之前对图像进行 base64 编码,那么它应该没问题。

看看下面的 fiddle ,使用了相同的请求,但是我在将第二个图像分配给范围之前对第二个图像的响应进行了 base64 编码(使用了 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);
});

注意:fiddle 只能在 Chrome 中运行,我不建议在客户端进行 base64 编码,最好在服务器端进行。

关于javascript - 如何使用数据 URI 将从 ApiController 检索到的内容绑定(bind)到 Angular 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com