我从web api返回HttpResponseMessage并在ajax调用中使用它,但得到空白的pdf。
我的ajax电话是
function downloadPDF()
{
$.ajax({
type: "POST",
crossDomain: true,
data: JSON.stringify(UserData),
url: rootUrl + "api/WebAPI/Export",
//dataType: "native",
contentType: "application/json",
//responseType: 'arraybuffer',
//contentType: "application/pdf",
headers: headers,
success: function (data) {
//document.write(data);
alert(data.size);
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Dossier_" + new Date() + ".pdf";
link.click();
}
}
答案 0 :(得分:1)
使用此函数将HttpResponseMessage(应为Base64String)转换为Array Buffer:
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
然后在转换为Array Buffer后调用此函数:
function saveByteArray(pdfName, byte) {
var blob = new Blob([byte], { type: "application/pdf" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = pdfName + ".pdf";
link.download = fileName;
link.click();
};
所以你的整个ajax调用将如下所示:
function downloadPDF()
{
$.ajax({
type: "POST",
crossDomain: true,
data: JSON.stringify(UserData),
url: rootUrl + "api/WebAPI/Export",
//dataType: "native",
contentType: "application/json",
//responseType: 'arraybuffer',
//contentType: "application/pdf",
headers: headers,
success: function (data) {
//document.write(data);
alert(data.size);
var bytes = base64ToArrayBuffer(data);
saveByteArray("Dossier_" + new Date(), bytes);
}
}