axios使用json下载文件流
- 定义:可以传递json。不适用于已有封装全局请求的axios
- 使用注意点:
- 声明responseType:'blob'.
- 使用Blob接收
- 动态文件名content-disposition接收。雷点:某些浏览器不会暴露该头部字段,需要服务器允许跨域访问该头部
axios({
headers: {
},
url: 'https://localhost/download/test',
method: 'post',
data: {
"headers": [
"姓名",
"年龄",
"城市"
],
"data": [
{
"姓名": "张三",
"年龄": 25,
"城市": "北京"
},
],
"fileName": "99"
},
responseType: 'blob',
withCredentials: true
}).then(response => {
console.log(response, 'response')
const disposition = response.headers['content-disposition']
let filename = 'aa.xlsx'
if (disposition && disposition.indexOf('filename=') !== -1) {
filename = disposition.split('filename=')[1].replace(/"/g, '')
filename = decodeURIComponent(filename)
}
const blob = new Blob([response.data], { type: response.headers['content-type'] })
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
window.URL.revokeObjectURL(url)
})
axios使用formData下载文件流
- 定义:类似于form提交下载
- 使用注意点:
- 声明Content-Type:'application/x-www-form-urlencoded'.
- 创建FormData传递参数
- 动态文件名content-disposition接收。参考json下载
var formData = new FormData();
formData.append("key","value")
axios({
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
},
url: 'http://localhost/api/download' ,
method: 'post',
data: formData,
responseType: 'blob',
withCredentials: true
}).then(response =>{
console.log(response,'response')
const blob = new Blob([response.data], { type: response.headers['content-type'] })
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = '游戏管理.xlsx'
document.body.appendChild(link)
link.click()
window.URL.revokeObjectURL(url)
})
form方式下载文件流
- 定义:form提交下载
- 使用注意点:
- 声明Content-Type:'application/x-www-form-urlencoded'.
- 创建FormData传递参数
- 动态文件名content-disposition接收。参考json下载
const paraData = { id: 1212, name: '测试名' }
console.log(paraData)
var form = document.createElement('form')
form.style.display = 'none'
form.action = gateUrl + '/api/dictData/downloadDictDataList'
form.method = 'post'
document.body.appendChild(form)
for (var key in paraData) {
if (paraData[key]) {
var input = document.createElement('input')
input.type = 'hidden'
input.name = key
input.value = paraData[key]
form.appendChild(input)
}
}
form.submit()
form.remove()