1、第一種方式是前端直接使用超鏈接:
<a href="user/downloadExcel">下載文件</a>
2、另一種情況是點擊文字調用方法,js動態(tài)創(chuàng)建a標簽:
<div class="downFile" onclick="downloadFile()">點擊下載</div>
function downloadFile(){
let a = document.createElement('a')
a.href = "user/downloadExcel"
a.click()
}
3、接口調用方法時:
function downloadFile(name){
axios({
method: 'get',
url: 'xxxx/xxx',
responseType: 'blob'
}).then(
response => {
let blob = new Blob([response.data])
if(window.navigator.msSaveOrOpenBlob){
navigator.msSaveBlob(blob,name)
}else{
let a = document.createElement('a')
a.href = window.URL.createObjectURL(blob)
a.download = name
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(a.href)
document.body.removeChild(a)
}
},
error => {
//reject(error)
}
)
}
注意事項:返回response可能直接是流,如果項目中調用錯誤,查看是否有axios配置了公共攔截導致沒有獲取到流數據,可修改攔截方法;如果下載成功,但是里面內容錯誤,有可能是response.data層級錯誤,測試是否去掉.data或加一層.data查看是否正常下載。