[英]Angular download pdf with Web API 2
我們正在嘗試從 web api v2 下載文件,然后使用“另存為”或在瀏覽器中自動下載任何解決方案都可以,但無法使任何解決方案起作用。
Chrome 中發生的事情什么都沒有,什么都不做 在 IE 中,我們收到提示“您是否要允許此網站在您的計算機上打開應用程序?” 單擊允許,然后什么也沒有發生。
這是 WebAPI 控制器代碼:
[HttpGet]
[Route("{pdf}/{getPDF}")]
public async Task<IHttpActionResult> GetPDF()
{
var outputpath = HttpContext.Current.Server.MapPath("~/");
HttpResponseMessage result;
using (FileStream stream = new FileStream(outputpath + "Inv_008618_180868_33687.pdf", FileMode.Open))
{
result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream),
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Inv_008618_180868_33687.pdf",
Size = stream.Length
};
return Ok(result);
}
}
我認為上面的代碼是正確的,但不是 100% 確定,因為文件大小非常小。
這是角代碼:
getPDF: function () {
var scope = this;
var urlApi = 'http://localhost:59242/supplier/pdf/';
return $http({
url: urlApi,
responseType: 'arraybuffer'
}).then(function (response) {
var file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
var pdf = $sce.trustAsResourceUrl(fileURL);
//var element = angular.element('<a/>');
//element.attr({
// href: 'data:attachment/pdf;charset=utf-8,' + encodeURI(response),
// target: '_self',
// download: 'test.pdf'
//})[0].click();
window.open(pdf);
}
return response.data;
})
.catch(function (err) {
})
}
我要感謝您的回復
使用 ngFileSaver 解決了這個問題,謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.