从C#Byte数组加载图像,并使用AngularJS将图像放在html标记中

我正在使用Byte Arrayforms的Image,因为我正在使用以下C#方法转换字节数组

public HttpResponseMessage ReturnBytes(byte[] bytes) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(bytes); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; } 

我的HTML源代码:

 
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.get("someurl") .then(function(response) { $scope.imageSrc = response.data; $('.div_image').html(''); }); });

参考链接我遵循:

  • 如何从C#中的Web Api方法正确获取字节数组?
  • 显示png图像作为对jQuery ajax请求的响应

我无法在HTML视图中加载图像。 请帮助我……

发送图像不是作为字节数组,而是转换Convert.ToBase64String字节数组并作为文本发送。 然后你的代码应该工作。

不要使用HttpResponseMessage()方法,只需将字节数组转换为Base64String,然后将其作为String类型响应发送回客户端。

C#源代码:

 [HttpPost] public string GetCalculatorResults() { byte[] imgArr = GetImageFromDataBase(); // Here we are converting the byte array to Base64String return Convert.ToBase64String(imgArr) } 

HTML和AngularJS源代码应该是

 

我测试了上面的代码,它的工作完美。