1.后台如果返回的是文件流
上图就是对应后台返回的二进制文件处理 res是后台返回的内容。
接口地址的请求需要加上 responseType: ‘blob’,
const blob = new Blob([res], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
})
const objectUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = objectUrl
a.download = '表'
a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
window.URL.revokeObjectURL(blob)
2.后台返回的是下载地址
downloadFile (fileName, content) {
let aLink = document.createElement('a')
let blob = this.base64ToBlob(content) // new Blob([content]);
let evt = document.createEvent('HTMLEvents')
evt.initEvent('click', true, true)// initEvent 不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = fileName
aLink.href = URL.createObjectURL(blob)
// aLink.dispatchEvent(evt);
aLink.click()
},