![](/img/trans.png)
[英]JQuery.ajax(): Issue with parameter data when consuming a WCF Service
[英]jQuery.ajax get image from wcf service and display
我正在尝试下载并显示使用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(); 在响应上显示错误:
字符串包含无效字符
谢谢。
正如Musa建议的那样,直接使用XMLHttpRequest可以达到目的。
var xhr = new XMLHttpRequest();
xhr.open('GET', apiURL + serviceDownloadFile.replace('{filename}', filename).replace('{pseudofilename}', fileNameExt), true);
xhr.responseType = 'blob';
xhr.setRequestHeader("authorization","xxxxx");
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
}
};
xhr.send();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.