最近遇见个下载文件后想要做些回调的事件,找了这样一个代码,用原生xhr发起请求,将文件下载传输过来,之后将blob转换为对象URL,模拟a链接点击事件,在下载中可以实现加载过程的动画,希望对你们有用。
XHRLoadFile(record:any){
let url = "127.0.0.1:8080/pig.png" //这里是文件地址
let xhr = new XMLHttpRequest()
xhr.open('get',url,true)
//如果需要请求头中,这里是token信息可以在这里设置
xhr.setRequestHeader('Content-Type','application/json,charset=UTF-8')
xhr.responseType = 'blob'
xhr.onreadystatechaneg = function(){
if(xhr.readyState === 4 && xhr.status === 2000){
const blob = new Blob([xhr.response])
let url = window.URL.createObjectURL(blob)
//创建一个a标签,设置下载属性,点击下载,最后移除元素
let link = document.createElement('a')
link.href = url
link.style.display = 'none'
//取出下载文件名
const name = xhr.getResponseHeader('content-disposition')
const filename = name.substring(name.lastIndexOf('=') + 1, name.length)
const downloadFile = decodeURIComponent(fileName)
link.setAttribute('download',downloadFileName)
link.click()
window.URL.revoKeObjectURL(url)
ctx.setState({loading:false})
}else if(xhr.status !==200){
ctx.setState({loading:false})
message.error('下载失败')
}
}
xhr.send()
}