点击按钮发送请求,服务器返回一个文件。如何保存这个文件的问题
通过a标签直接定位到服务器上的文件原则上也是可以的
1.使用Axios封装的请求函数
// request是一个axios实例,返回一个promise
export function getConfigFile(){
return request({
url: "cgi-bin/configfile"
method: "get",
// 需要设置responseType
responseType: "blob"
})
}
2.点击按钮,触发时间,调用函数发送请求下载文件
// 按钮绑定的函数为downloadFile
function downloadFile(){
getConfigFile().then(res => {
// 获取到文件名(文件名放在请求头中)
let file_name = res.headers['content-disposition'].split("=")[1]
// 获取到文件
let file = res.data
// 通过blob保存
const blob = new Blob([file])
if('download' in document.createElement("a")){
// 非IE下载
const elink = document.createElement("a")
elink.download = file_name
elink.style.display = "none"
// 表示一个指定的File对象或Bolob对象
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
}else{
// IE10+下载
navigator.msSaveBlo(blob, file_name)
}
}).catch(err => {
console.log("请求文件失败!")
})
}