下载文件一般有两种方式:
这里讲的就是方法 2。
// 传入流数据,下载为文件
function downBlob(data: Blob, type: string, fileName: string) {
let blob = new Blob([data], { type });
let url = window.URL.createObjectURL(blob)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象
}
// 某页面文件中
import axios from 'axios'
import downBlob from './utils'
(async () => {
// 请求接口
let response = axios({
url: '接口',
method: 'post',
responseType: 'blob', // 关键,此处设置此项,axios 会正确处理好数据
})
let {data, headers} = response
// 下载
downBlob({
data,
contentType: headers?.['content-type'], // 获取此文件类型
// content-disposition 为后台需要添加的一个详情头,有这个文件的文件名信息
// 获取文件名,然后使用 decodeURIComponent 方法解码
fileName: decodeURIComponent(headers?.['content-disposition']?.match(/filename\*=([\s\S]*)/)?.[1]) || '未知文件',
})
})()