【應用場景】
選中表格的一條數據,然后點擊下載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