[英]How to bind a byte[]/ Memory stream to image src attribute in Javascript
I have an ActionMethod which can return a Memorystream or byte[] of an image. 我有一个ActionMethod,它可以返回Memorystream或图像的byte []。 This action method is called on ajax.
在ajax上调用此操作方法。 Now I want to bind this image to an image tag src attribute.
现在,我想将此图像绑定到图像标签src属性。
public ActionResult GetBpChart(string Timespan)
{
var ObjMemoryStream = new MemoryStream();
try
{
ObjMemoryStream = MyModel.GetImage(Timespan);
}
catch (Exception Ex)
{
}
//return Content(Convert.ToBase64String(ObjMemoryStream.GetBuffer()));
//return Json(ObjMemoryStream.GetBuffer());
return File(ObjMemoryStream.GetBuffer(), "image/jpeg");
}
function GetChart() {
try {
$.ajax({
type: 'POST',
url: "myActionMethodurl",
data: {
Timespan: $('#ddlBpTimespan').val()
},
success: function (ImgSrc) {
// For Base64String
//$('#divBpChart').innerHTML = '<img src= "data:image/jpeg;base64," ' + ImgSrc + '"/>';
// For Json of byte[]
//$('#divBpChart').innerHTML = '<img src= "data:image/gif;base64," ' + ImgSrc + '"/>';
// For FileContentResult
$('#imgBpChart').attr('src', ImgSrc);
HideAjaxProgress();
}
});
} catch (E) {
}
}
I tried the above 3 combinations. 我尝试了以上3种组合。 But no luck.
但是没有运气。 Can someone say what I am missing here or what's the correct way to achieve this
有人可以说我在这里想念的东西还是实现此目的的正确方法是什么
From reading the .ajax() docs, I would say the simple answer is " no, you can't do that. " 通过阅读.ajax()文档,我会说简单的答案是“ 不,你不能那样做。 ”
Luckily, you don't need to. 幸运的是,您不需要。 Just create the relevant URL and update the target image's
src
attribute: 只需创建相关的URL并更新目标图像的
src
属性即可:
function GetChart() {
try {
var ImgSrc = '/mycontroller/myActionMethodurl?timespan=' + $('#ddlBpTimespan').val();
$('#imgBpChart').attr('src', ImgSrc);
} catch (error) {
}
}
If you're coding this within a View, you can leverage the UrlHelper to help build the correct "base" URL: 如果在View中进行编码,则可以利用UrlHelper帮助构建正确的“基本” URL:
function GetChart() {
try {
var ImgSrc = '@Url.Action("myActionMethodurl", "mycontroller")?timespan=' + $('#ddlBpTimespan').val();
$('#imgBpChart').attr('src', ImgSrc);
} catch (error) {
}
}
For a plain JavaScript method that seems to work, refer to Using jQuery's ajax method to retrieve images as a blob . 对于似乎可行的普通JavaScript方法,请参阅使用jQuery的ajax方法以blob形式检索图像 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.