处理方案:异步下载,设置 responseType = 'blob'
<template>
<div>
<h1 @click="xhrDownload"> xhr 异步下载 json 等资源文件</h1>
<h1 @click="axiosDownload">axios 异步下载 json 等资源文件</h1>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'DownloadFile',
methods: {
axiosDownload () {
// config 是配置对象,可按需设置,例如 responseType,headers 中设置 token 等
const config = {}
// 这一步可能很关键,特别是在能下载,但是下载下来打开异常的时候。
config.responseType = 'blob'
axios.get('http://localhost:8278/package.json', config).then(res => {
const blob = new Blob([res.data]) // 将字节流(字符流)转换为 blob 对象
this.blobDownload(blob)
})
},
/**
* 下载文件:下载 blob 对象形式的文件
* @param blob
* @param filename
*/
blobDownload (blob, filename = '文件.json') {
let url = window.URL.createObjectURL(blob)
// 解决 ie 不支持下载 blob资源
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(blob, filename)
return
}
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象
},
xhrDownload (params) {
// token 等header 参数和 请求方式都可以按需配置
const token = localStorage.getItem('token') || ''
const url = 'http://localhost:8278/package.json'
let xhr = new XMLHttpRequest()
// get 方式
xhr.open('get', url + '?timeStamp=' + new Date().getTime(), true)
xhr.setRequestHeader('Cache-Control', 'no-cache')
xhr.setRequestHeader('Content-type', 'application/json')
// xhr.setRequestHeader('kms-token', token)
// 返回类型blob,不设置会打不开 excel
xhr.responseType = 'blob'
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
// 请求完成
if (this.status === 200) {
let blob = this.response
let url = window.URL.createObjectURL(blob)
// 生成 url,创建一个a标签用于下载
let a = document.createElement('a')
a.download = '收支清单.json'
a.href = url
a.click()
}
}
xhr.send(JSON.stringify(params))
}
}
}
</script>