在前端业务中,通常会有通过后端返回的文件流,下载文件或附件到本地的需求。
以下是通过js实现的一些步骤:
1. 使用axios 发送请求
先确定请求的方法(get/post/patch 等)。
因为 axios 默认设置的responseType 为 json ,因为前端想获取文件流类别的响应,需要设置为 responseType : 'blob'
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
axios中每种方法设置配置的方法不同:
axios.request(config)axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.options(url[, config])axios.post(url[, data[, config]])axios.put(url[, data[, config]])axios.patch(url[, data[, config]])
将config 参数设置为 {responseType : 'blob'}。
2. 具体怎么拿到响应的结果,要看一下项目中设置的 axios 响应拦截器
//响应拦截器
axios.interceptors.responce.use(
function (responce){
...
const arr = [
"application/x-download;chartset=utf-8",
"application/octet-stream;chartset=utf-8",
...
]
if(responce.headers && responce.headers["content-type"]){
return {
data: responce.data,
headers: responce.headers
}
}
}
)
const res = await downloadFile()
res // {data:...,headers: ...}
//通过res.data 拿到文件流 blob
3. 下载文件(通过动态创建a标签)
function download(){
...
const link = document.createElement('a')
// res.data 为拿到的blob 文件流数据
const url = URL.createObjectURL(res.data)
link.herf = url
link.download = '文件名'
link.style.display = 'none'
document.body.appendChild(link)
link.click()
//下载完成释放内存
document.body.removeChild(link)
URL.revokeObjectURL()
}