接口书写 , 注意接口添加 responseType: 'arraybuffer'
import { axios } from '@/utils/request' export const downloadStandard = () => { return axios.get(`${DATAEXCHANGE}/demandManagement/downloadFile?fileName=pg字段对接.txt`, { responseType: 'arraybuffer' }) }
点击下载触发自定义事件 , 获取数据 ,如果不经过resolveBlob方法处理 , res的中文是乱码状态
downloadStandard().then((res) => {
resolveBlob(res, 'arraybuffer', 'xxx.txt')
})
处理res数据 , 使用resolveBlob即可
import axios from 'axios'
import storage from 'store'
const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
const url = baseUrl + str
axios({
method: 'get',
url: url,
responseType: 'blob',
headers: { Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN_AUTH) }
}).then((res) => {
resolveBlob(res, mimeMap.zip)
})
}
/**
* 解析blob响应内容并下载
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
* @param {String} fileName 文件名
*/
export function resolveBlob(res, mimeType, fileName) {
const aLink = document.createElement('a')
const blob = new Blob([res.data], { type: mimeType })
if (!fileName) {
const patt = /filename=([^;]+\\.[^\\.;]+);*/
const contentDisposition = decodeURI(res.headers['content-disposition'])
const result = patt.exec(contentDisposition)
fileName = result[1].replace(/"/g, '')
}
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.appendChild(aLink)
}