1、需求描述
管理系统需要完成文件的导出(下载)功能,前端通过axios怎样解决文件的下载功能;
2、 问题分析
下载其实是浏览器的内置事件,浏览器的 GET请求(frame、a)、 POST请求(form)具有如下特点:
- response 会交由浏览器处理;
- response 内容可以为二进制文件、字符串等。
3、 解决方案
要在 axios 的 config 配置 responseType: ‘blob’ (非常关键),服务端读取文件,以 content-type: ‘application/octet-stream’ 的格式返回前端,前端接收到数据后使用 Blob 来接收数据,并且创建a标签进行下载。
4、代码实现
后端这里以express举例
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
// 以post提交举例
app.post('/info/download', function(req, res) {
const filePath = './myfile/test.zip'
const fileName = 'test.zip'
res.set({
'content-type': 'application/octet-stream',
'content-disposition': 'attachment;filename=' + encodeURI(fileName)
})
fs.createReadStream(filePath).pipe(res)
})
app.listen(3000)
前端解析数据流,主要使用 Blob 对象来进行接收,示例代码如下:
// 以之前的post请求举例
axios.post(url, {...someData}, {responseType: 'blob'})
.then((res) => {
const { data, headers } = res
const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1')
// 此处当返回json文件时需要先对data进行JSON.stringify处理,其他类型文件不用做处理
//const blob = new Blob([JSON.stringify(data)], ...)
const blob = new Blob([data], {type: headers['content-type']})
let dom = document.createElement('a')
let url = window.URL.createObjectURL(blob)
dom.href = url
dom.download = decodeURI(fileName)
dom.style.display = 'none'
document.body.appendChild(dom)
dom.click()
dom.parentNode.removeChild(dom)
window.URL.revokeObjectURL(url)
}).catch((err) => {})
如果后台返回的流文件是一张图片的话,前端需要将这张图片直接展示出来,例如登录时的图片验证码,示例代码如下:
axios.post(url, {...someData}, {responseType: 'blob'})
.then((res) => {
const { data } = res
const reader = new FileReader()
reader.readAsDataURL(data)
reader.onload = (ev) => {
const img = new Image()
img.src = ev.target.result
document.body.appendChild(img)
}
}).catch((err) => {})