1.onload
const {url, name} = this.file
let x = new XMLHttpRequest()
x.open('GET', `/api/download?path=${url}`, true)
x.responseType = 'blob'
x.onload = function () {
let url = window.URL.createObjectURL(x.response)
let a = document.createElement('a')
a.href = url
a.download = name // 名字可自定义
a.click()
}
x.send()
2.iframe,需要后端配合改http头
// 前端js:
const {url, name} = this.file
const iframe = document.createElement('iframe')
iframe.style.display = 'none' // 防止影响页面
iframe.style.height = 0 // 防止影响页面
iframe.src = `/api/download?path=${url}&name=${name}`
document.body.appendChild(iframe) // 这一行必须,iframe挂在到dom树上才会发请求
// 5分钟之后删除
setTimeout(() => {
iframe.remove()
}, 5 * 60 * 1000)
// 后端java:
response.setHeader("Content-Disposition","attachment; filename="+name)