【发布时间】:2015-01-21 02:57:51
【问题描述】:
我正在尝试使用 jQuery.ajax 下载并显示从 wcf 服务返回的图像。我无法使用收到的数据,我不知道为什么。我尝试了很多东西,但似乎没有任何效果。
这里的服务:
public Stream DownloadFile(string fileName, string pseudoFileName)
{
string filePath = Path.Combine(PictureFolderPath, fileName);
if (System.IO.File.Exists(filePath))
{
FileStream resultStream = System.IO.File.OpenRead(filePath);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-www-form-urlencoded";
return resultStream;
}
else
{
throw new WebFaultException(HttpStatusCode.NotFound);
}
}
这里是我的 ajax 调用:
$.ajax({
type: "GET",
url: apiURL + serviceDownloadFile.replace('{filename}', filename),
headers: headers,
contentType: "application/x-www-form-urlencoded",
processData : false,
success: function(response) {
var html = '<img src="data:image/jpeg;base64,' + base64encode(response) +'">';
$("#activitiesContainer").html(html);
},
error: function (msg) {
console.log("error");
console.log(msg);
}
});
将 url 放入 <img> 标记中确实可以正确显示图像,但由于该服务需要授权标头,因此该页面每次都要求我提供凭据。
所以我的问题是,如何处理响应数据以便我可以显示它?使用 btoa();在响应上显示错误:
字符串包含无效字符
谢谢。
【问题讨论】:
-
为什么响应 contentType 是
"application/x-www-form-urlencoded"?不清楚身份验证问题是什么。假设它被发送的标头覆盖? -
因为服务可以返回任何类型的文件,但是对于这个特定的部分,我确定文件是图像。没有身份验证问题,问题出在我收到的数据上。
-
图片与表单编码有什么关系?
-
我不知道..这对我来说很新。而且我没有对服务进行编码,其他人做了。我几乎在做一些我不太了解的事情..
-
嗯,你不能用 jQuery 做到这一点,你必须使用裸 XHR2
标签: javascript jquery ajax wcf