get请求是H5代码。可能会出现跨域问题,让服务端解决跨域问题,还有很多浏览器不支持,目前只有少数的几个浏览器支持下载
downFile (info) {
let url = info.downPath//文件下载地址
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "blob";
xhr.onload = function () {
let blob = xhr.response
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, info.fileName)
} else {
let link = document.createElement('a')
let evt = document.createEvent('HTMLEvents')
evt.initEvent('click', false, false)
link.href = URL.createObjectURL(blob)
link.download = info.fileName
link.style.display = 'none'
document.body.appendChild(link)
link.click()
window.URL.revokeObjectURL(link.href)
}
};
xhr.send();
},
post请求是web端的,后端接口地址返回来的是文件流,没办法只能用这种方式,测试通过没问题
downOut () {
const env = process.env.VUE_APP_ENV
let url = config.baseUrl[env] + "Device/ExportDevice"//接口请求地址
const req = new XMLHttpRequest();
let formData = JSON.stringify(this.selectedRowKeys);//post请求参数
req.open('POST', url, true);
req.responseType = 'blob';
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('token', localStorage.getItem('sysToken'))//携带token参数
req.onload = () => {
const data = req.response;
const blob = new Blob([data], { type: "application/octet-stream" });
const blobUrl = window.URL.createObjectURL(blob);
this.download(blobUrl);
};
req.send(formData);
},
download (blobUrl) {
const a = document.createElement('a');
a.style.display = 'none';
a.download = '批量导出设备信息.xlsx'; //文件名
a.href = blobUrl;
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(a.href)
},