【问题标题】:Download PDF file is not working with angular and JavaScript下载 PDF 文件不适用于 Angular 和 JavaScript
【发布时间】:2018-04-19 11:06:06
【问题描述】:
我正在使用以下代码下载 PDF 文件。文件已下载但不包含任何数据。
var blob = new Blob([response], { type: "text/plain"});
var url = window.URL.createObjectURL(blob);
var link = document.createElement('a');
link.href = url;
link.download = e.coAttachmentName;
link.click();
【问题讨论】:
标签:
javascript
angularjs
blob
【解决方案1】:
使用 FileSaver.js,从这里获取它https://github.com/eligrey/FileSaver.js/
var filename = new Date();
var blob = new Blob([response], {type: "application/pdf;charset=utf-8"});
saveAs(blob, filename +".pdf");
saveAs 将为您下载一个 pdf 文件。
【解决方案2】:
首先,您的请求响应类型必须是arraybuffer。
function openFile(response,fileName,saveFile){
var fileURL;
var contentType = response.headers('Content-Type');
var blob = new $window.Blob([response.data], { type: contentType });
if(saveFile){
saveAs(blob, fileName);
}else{
if($window.navigator.msSaveOrOpenBlob){
$window.navigator.msSaveOrOpenBlob(blob , fileName);
}else{
fileURL = URL.createObjectURL(blob);
$window.open(fileURL, '_blank');
}
}
}
$window 是一个 AngularJS 服务 - 引用浏览器 window 对象。
$window.navigator.msSaveOrOpenBlob - 这是一种特定于 IE 浏览器的方法,支持创建和下载 IE 不支持的 Blob URL 文件。
saveAs - https://github.com/eligrey/FileSaver.js/