[英]jQuery.ajax get image from wcf service and display
I'm trying to download and display an image that is returned from a wcf service using jQuery.ajax. 我正在尝试下载并显示使用jQuery.ajax从wcf服务返回的图像。 I'm not able to work with the data I've received and I'm not sure why.
我无法处理收到的数据,也不确定为什么。 I've tried a lot of things but nothing seems to work.
我已经尝试了很多东西,但似乎没有任何效果。
Here the service : 这里的服务:
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);
}
}
Here my ajax call : 这里我的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);
}
});
Putting the url in a <img>
tag does display the image properly, but since the service requires an authorization header, the page ask me for credentials each time. 将url放在
<img>
标记中可以正确显示图像,但是由于该服务需要授权标头,因此该页面每次都要求我提供凭据。
So my question is, what to do this the response data so I can display it ? 所以我的问题是,该怎么做才能显示响应数据? using btoa();
使用btoa(); on the response displays an error :
在响应上显示错误:
string contains an invalid character
字符串包含无效字符
Thanks. 谢谢。
As suggested by Musa, using XMLHttpRequest directly did the trick. 正如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.