// 文件下载
downloadPdf(id: number) {
this.http.post('/api/documents', { id })
.subscribe(
(base64Pdf: string) => {
const arrayBuffer = base64ToArrayBuffer(base64Pdf); // 创建Array缓冲区
createAndDownloadBlobFile(arrayBuffer, 'testName');
},
error => console.error(error)
)
}
// Base64到数组缓冲区
export function base64ToArrayBuffer(base64: string) {
const binaryString = window.atob(base64); //如果不使用base64,则注释这个
const bytes = new Uint8Array(binaryString.length);
return bytes.map((byte, i) => binaryString.charCodeAt(i));
}
// 创建Blob对象并下载文件
createAndDownloadBlobFile(body, filename, extension = 'pdf') {
const blob = new Blob([body]);
const fileName = `${filename}.${extension}`;
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, fileName);
} else {
const link = document.createElement('a');
//支持HTML5下载属性的浏览器
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
angular文件下载
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 之前在工作的时候,有个需求是将查询出来的列表下载到本地,那么这个方法也就产生:以下是代码片段: No.1 以下这部...
- 在项目里遇到附件的下载和本地查看功能,附件有可能是word pdf 图片 Excel表格 甚至是ppt 有点变态吧...