1. get形式传参数
仅限于get方式,注意请求头参数...,需要后台放开
window.location = \'/dms-underlying-asset/download?assetType=\' + localStorage.getItem(\'assetType\')
2. post形式传参数
前端项目中使用最多的
注意:请求类型:responseType: "blob"
(1)定义接口(post请求,responseType:数据返回类型为blob)
1 export function download(data) { 2 return request({ 3 url: `api/exportExcel`, 4 method: \'post\', 5 responseType: \'blob\', 6 data 7 }) 8 }
(2)调用接口
1 const res = await download(this.form) 2 // 等同于 3 // axios.post(\'/api/exportExcal\', this.form, {responseType: //"blob"}).then(res => {}) 4 5 console.log(res, \'这里会看到返回的blob文件流\') // 类似这种
6 7 if (!res) return // 8 const excelTitle = "嘤嘤嘤.xlsx" 9 10 this.readFileDownload(res, excelTitle) // 封装读取文件并下载
(3)封装读取文件并下载
这里涉及到几个问题:
1. FileReader 读取bolb流文件,参考:https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。
2. content-type(res.type === \'application/octet-stream\')我们在解析res.type的时候,参考:https://blog.csdn.net/u012894692/article/details/88846401
export function readFileDownload(data, msg) { var res = data if (res.type === \'application/json\' || res.type === \'application/json;charset=UTF-8\') { // 失败的时候,注意ie兼容问题
let fileReader = new FileReader() fileReader.onload = function(event) { let jsonData = JSON.parse(this.result) // this.result是根据event,读取文件后打印的 console.log(jsonData, \'...............\') if (jsonData.data === null && jsonData.code === 1) { Message({ message: jsonData.msg || \'Error\', type: \'error\', duration: 5 * 1000 }) } } fileReader.readAsText(res)
} if (res.type === \'application/octet-stream\' || res.type === \'application/vnd.ms-excel\' || res.type === \'application/vnd.ms-excel;charset=UTF-8\') { console.log(\'success...\') // 成功,注意ie兼容问题 const blob = new Blob([res], { type: \'application/vnd.ms-excel;charset=utf-8\' }) if (window.navigator && window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, msg) } else { console.log(blob) const url = window.URL.createObjectURL(blob) console.log(url) const aLink = document.createElement(\'a\') aLink.style.display = \'none\' aLink.href = url aLink.setAttribute(\'download\', msg) document.body.appendChild(aLink) aLink.click() document.body.removeChild(aLink) window.URL.revokeObjectURL(url) } } }
3,将表格的下载成excel表格(table表格绑定id)
这种方式怎么说呢,感觉不实用,仅限于前端页面的table表格,在没有后台接口的情况下,(有分页的话还比较难搞),不实用
// 导出表格 var wb = XLSX.utils.table_to_book(document.querySelector(\'#mytable\')) //mytable为表格的id名 var wbout = XLSX.write(wb, { bookType: \'xlsx\', bookSST: true, type: \'array\' }) try { FileSaver.saveAs(new Blob([wbout], { type: \'application/octet-stream\' }), \'统计表.xlsx\') } catch (e) { if (typeof console !== \'undefined\') console.log(e, wbout) } return wbout