下载文件两种方式: js-file-download、blob
import axios form 'axios'
import qs from 'qs'
// 参数
const body = {
fileId: this.fileId
}
get方式下载:( js-file-download )
try {
axios.get('url', { params: body, responseType: 'arraybuffer' }).then(res => {
JsFileDownload(res.data, `测试文件_${new Date().toLocaleString()}.xls`)
})
} catch (e) { throw new Error(e) }
post 方式下载:( js-file-download )
axios({
url: '/api/system/file/download/by/fileId',
method: 'post',
data: qs.stringify(body),
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
},
responseType: 'arraybuffer'
}).then(res => {
JsFileDownload(res.data, `解析错误文件详情_${new Date().toLocaleString()}.xls`)
})
post 方式下载:( blob / 不用qs序列化参数)
axios({
url: '/api/system/file/download/by/fileId',
method: 'post',
data: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;',
},
responseType: 'arraybuffer',
transformRequest: [function (body) {
let ret = ''
for (let it in body) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(body[it]) + '&'
}
return ret // 必须返回字符串
}]
}).then(res => {
var blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'}); //指定格式为vnd.ms-excel
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href
downloadElement.download = '测试文件.xls'; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
})
附:
axios: https://github.com/axios/axios#request-method-aliases