原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处
虽然前后端分离,但是下载文件我们一般要求是在登陆状态下,然后又是把token往header中传,所以window.location不能带header参数的方式实现起来,业务体验下很差,并不符合要求。
我们预期最佳的效果是如果业务异常,则直接友好弹出提示,如果业务正常,则直接下载文件
下面这个代码案例百度少有,我觉得应该是业界最佳实践了。
//请求后台接口 这个接口要后台约定返回格式 注意responseType = blob
export function createLicense (parameter) {
return axios({
url: '/customer/machine/createLicense/' + parameter,
method: 'post',
responseType: 'blob'
})
}
//vue方法
handleDownload (record) {
createLicense(record.id).then(res => {
//如果后台返回的是json格式,则证明业务异常
if (res.type === 'application/json') {
var reader = new FileReader()
reader.onload = e => {
const result = JSON.parse(e.target.result)
this.$message.error(result.msg)
}
reader.readAsText(res)
}
//如果后台返回的是文件流 则正常下载
else {
const url = window.URL.createObjectURL(new Blob([res]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'license.zip')
document.body.appendChild(link)
link.click()
}
})
},
2.平时的上传组件,很难用axios,都是自带上传 所以配置多个全局变量就好了,
并且挂载在vue上:
Vue.prototype.$baseUrl = process.env.VUE_APP_API_BASE_URL