如何使用$ .ajax将image src设置为动态图像/ png数据? [英] How can I use $.ajax to set image src to dynamic image/png data?
问题描述
使用少量用户输入参数动态生成图像。我能够通过 GET 成功生成图像,写入 Response.OutputStream
Images are generated dynamically with a handful of user input parameters. I'm able to successfully produce the image via GET, by writing to Response.OutputStream
$('#myImage').attr('src', 'Images/GetImage?param1=value1¶m2=value2');
还有其他几个参数。但是,我如何通过 POST 来实现这一目标?我以为我可能会使用 $。ajax
和base64编码 Image
,但它不能正常工作。
There are several additional parameters. But, how can I accomplish this with a POST? I thought I might use $.ajax
and base64 encode the Image
, but it doesn't quite work.
$.ajax({
url: 'Images/GetImage64',
type: 'POST',
data: { param1: 'value1', param2: 'value2' },
success: function (data) {
//$('#myImage').attr('src', data);
$('#myImage').attr('src', 'data:image/png;base64, ' + data);
}
});
Chrome开发工具显示带有text / plain响应的/ Images / GetImage64的ajax(XHR)POST 。内容类似于服务器上生成的PNG。但是,另一个其他请求是使用下面的URL进行的,我不知道发生了什么
Chrome dev tools shows an ajax (XHR) POST to /Images/GetImage64 with a text/plain response. The content looks like the PNG generated on the server. However, another "Other" request is made with the URL below, and I have no idea what's going on
data:image/png:base64, [binary]
在服务器上,我返回 ImageResult:ActionResult
覆盖 ExecuteResult
并使用base64编码的图像进行响应。
On the server, I'm returning an ImageResult : ActionResult
that overrides ExecuteResult
and response with base64 encoded image.
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = "text/plain";
context.HttpContext.Response.BinaryWrite(GetBase64Image(Image));
}
推荐答案
可能是jQuery的错。尝试强制jQuery将结果视为纯文本,使用 dataType:'text'
:
Might be jQuery's fault. Try forcing jQuery to treat the result as plain text with dataType: 'text'
:
$.ajax({
url: 'Images/GetImage64',
type: 'POST',
dataType: 'text',
data: { param1: 'value1', param2: 'value2' },
success: function (data) {
$('#myImage').attr('src', 'data:image/png;base64,' + data);
}
});
编辑:没关系,不是那样。
Nevermind, wasn't that.
这篇关于如何使用$ .ajax将image src设置为动态图像/ png数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!