前端请求下载文件的方式

使用 fetch

fetch('//xxx.xxx.com/10.pdf', {
mode: 'cors'
}).then(res => res.blob()).then(blob => {
const blobURL = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.style.display = 'none'
link.href = blobURL
link.setAttribute('download', decodeURI('10.pdf'))
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
window.URL.revokeObjectURL(blobURL)
})

使用封装好的 $http

$http({
// 防止出现协议问题,这里不要写具体的 http 或者 https
url: '//xxx.xxx.com/10.pdf',
headerType: 'download',
method: 'get',
// 不指定默认从 content-disposition 头读取,后端接口也必须要设置 content-disposition 才能读取到
fileName: 'download.docx'
}).then(res => {

})

window.open

缺点:需要同域、可能会被拦截、浏览器支持预览的文件不会直接下载

window.open('//xxx.xxx.com/10.pdf')

form 表单提交

缺点:浏览器支持预览的文件不会直接下载

export function download (url, params = {}) {
const form = document.createElement('form')
form.method = 'post'
form.action = url
form.target = '_blank'
document.body.appendChild(form)
for (const key in params) {
const value = params[key]
if (value) {
const input = document.createElement('input')
input.setAttribute('type', 'hidden')
input.setAttribute('name', key)
if (isArray(value)) {
input.setAttribute('value', stringify(value))
} else {
input.setAttribute('value', value)
}
form.appendChild(input)
}
}
form.submit()
document.body.removeChild(form)
}

a 标签触发

缺点:可能会被拦截、浏览器支持预览的文件不会直接下载

const link = document.createElement('a')
link.style.display = 'none'
link.href = '//xxx.xxx.com/10.pdf'
link.setAttribute('download', decodeURI('10.pdf'))
document.body.appendChild(link)
link.click()
document.body.removeChild(link)

1 和 2 的方式,无论什么文件都是执行下载