.net webapi后台返回pdf文件流,前端ajax請求下載,空白pdf排錯經歷
先上代碼:
后台webapi代碼:
[HttpGet]
[Route("{manifestId}")]
public IHttpActionResult FindManifestPdfById([FromUri]string manifestId)
{
byte[] result = _manifestService.GetData(manifestId);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(result));
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = manifestId + ".pdf",
};
return this.ResponseMessage(response);
}
前端代碼:這邊用的是angularjs,實現代碼大同小異
function downloadFile(manifestUrl) {
$http({
url: manifestUrl,
method: 'GET',
responseType: "blob",
params: {},
headers: {
'Content-Type': 'application/pdf',
}
}).success(function (response, status, headers, config) {
Export(response, 'abc.pdf');
}).error(function (response) {
});
}
//文件流下載
function Export(blob, fileName) {
if ('download' in document.createElement('a')) { // 非IE下載
var elink = document.createElement('a');
elink.setAttribute("download", fileName);
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);// 釋放URL 對象
document.body.removeChild(elink);
} else { // IE10+下載
navigator.msSaveBlob(blob, fileName);
}
}
這邊最最最重要的一行代碼是請求時添加responseType: "blob",參數。
之前沒有添加:
通過返回的response組裝blob
var blob = new Blob([data], {type: 'application/pdf'});
出來的標簽死活是空白pdf,個人感覺是沒有傳responseType參數,服務器傳回來的類型變成了字符串,再通過數組轉成Blob時,編碼就會異常,返回了空白pdf。
pdf流字符串顯示形式
主要參考的文章有:
https://stackoverflow.com/questions/34436133/pdf-is-blank-when-downloading-using-javascript
responseType說明
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType