I'm trying to download and display an image that is returned from a wcf service using jQuery.ajax. 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.
我正在尝试使用jQuery.ajax下载并显示从wcf服务返回的图像。我无法使用我收到的数据,我不知道为什么。我尝试过很多东西,但似乎没什么用。
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放在标记中会正确显示图像,但由于该服务需要授权标题,因此该页面每次都会询问我的凭据。
So my question is, what to do this the response data so I can display it ? using btoa(); on the response displays an error :
所以我的问题是,如何处理响应数据,以便我可以显示它?使用btoa();在响应上显示错误:
string contains an invalid character
string包含无效字符
Thanks.
1 个解决方案
#1
0
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();
#1
0
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();