【发布时间】:2014-02-11 10:56:23
【问题描述】:
我有一个 asp.net 页面。
在此页面内,我有一个 img 控件/元素。
我正在我的服务器上调用一个 ashx 页面。
此 ashx 页面接受来自客户端的时间戳并将其与存储在服务器上的时间戳进行比较。
如果时间戳不匹配,则返回已转换为字节数组(在 C# 中)的图像。
如果时间戳不匹配,则返回字符串值“-1”。
所以,这是我的 ashx 页面的精简版:
public void ProcessRequest (HttpContext context) {
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
try
{
string clientTS = context.Request.QueryString["clientTS"];
if (clientTS == serverTS)
{
//new version available. refresh browser
context.Response.ContentType = "text/json";
string value = "-1";
context.Response.Write(value);
}
else
{
context.Response.ContentType = "image/jpg";
byte[] data = Shared.GetMobileNextFrame("par1", 0);
context.Response.BinaryWrite(data);
}
}
catch (Exception ex)
{
context.Response.ContentType = "text/json";
context.Response.Write("ERR");
}
}
在我的 javascript 代码中:
function GetImageStatus() {
finished = false;
var val = url + '/Mobile/isNewFrame.ashx?Alias=' + Alias + '&CamIndex=' + camIndex + '&Version=' + version + '&GuidLogOn=' + guidLogOn;
$.ajax({
url: val,
type: 'GET',
timeout: refreshWaitlimit,
data: lastTS,
success: function (response, status, xhr) {
var ct = xhr.getResponseHeader("content-type");
if (ct.indexOf('json') > -1) {
//no update
}
else {
try {
live1x4.src = 'data:image/bmp;base64,' + encode(response);
}
catch (err) {
alert(err);
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
//handle error
}
});
}
function encode(data) {
var str = String.fromCharCode.apply(null, data);
return btoa(str).replace(/.{76}(?=.)/g, '$&\n');
}
但我得到一个错误返回:
TypeError: Function.prototype.apply: Arguments list has wrong type
如果我只是申请:
live1x4.src = 'data:image/bmp;base64,' + btoa(response);
代替:
live1x4.src = 'data:image/bmp;base64,' + encode(response);
我收到此错误:
InvalidCharacterError:btoa 失败。要编码的字符串包含 超出 Latin1 范围的字符。
我已尝试使用画布控件和我在此站点上找到的示例代码。我没有收到错误消息,但我也没有收到图像。
我知道图像是有效的,因为我的旧代码将 image.src 直接指向 ashx 处理程序(而且我没有比较时间戳)。
我不想在服务器上将字节数组编码为 base64 字符串,因为这会使下载数据膨胀。
我想知道我是否使用了错误的 context.Response.ContentType,但我看不出我还能使用什么。
我做错了什么?
【问题讨论】:
标签: javascript image ashx