前端请求下载文件的方式
使用 fetch
fetch('//xxx.xxx.com/10.pdf', { |
使用封装好的 $http
$http({ |
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 的方式,无论什么文件都是执行下载