vue + element ui 实现pdf文件下载和预览


【应用场景】

选中表格的一条数据,然后点击下载pdf文件,实现下载功能

 

一:pdf文件下载功能

1、后端接口地址,首先在axios.post的请求中把默认的 " responseType:‘json’ " 改为" responseType:‘blob’ 

如果是其他文件格式,参考MIME多用途互联网邮件扩展类型。

/** * 导出Pdf文件 */ export const getImportPdf = (id) => { return request({ url: '/api/lh-customs/ExportPdf/downloadHfd?id=' + id, method: 'get', responseType: 'blob' }) }

并且,后端接口返回的是文件流的形式

 

2、按钮方法代码

<el-button type="primary" size="mini" icon="el-icon-download" @click="importPdf">下载PDf文件</el-button>

// 导出pdf功能
importPdf() { if (this.selectionList.length === 0 || this.selectionList.length > 1) { this.$message.warning("请选择一条数据") return } getImportPdf(this.selectionList[0].id).then(res => { // 下载pdf //type类型可以设置为文本类型,这里是pdf类型 this.pdfUrl = window.URL.createObjectURL(new Blob([res.data], { type: `application/pdf` })); const fname = ``; // 下载文件的名字 const link = document.createElement('a'); link.href = this.pdfUrl; link.setAttribute('download', fname); document.body.appendChild(link); link.click(); })
},

 

二:pdf文件预览

downLoadPdf() { if (this.selectionList.length === 0 || this.selectionList.length > 1) { this.$message.warning("请选择一条数据") return } getImportPdf(this.selectionList[0].id).then(res => {
   const binaryData = [];
   binaryData.push(res);
 //获取blob链接 this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' })); window.open(this.pdfUrl);
 }) },

 

补充知识:MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。

网页链接:https://www.cnblogs.com/yjmBlogs/p/9493726.html

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM