文件下载
2019-11-12 本文已影响0人
那头黑马
const getFile = url => {
return new Promise((resolve, reject) => {
axios.get(url, {params: data}).then(data => {
if (data.data) {
resolve(data.data);
} else {
message.error('获取文件失败');
}
}).catch(error => {
message.error('获取文件失败');
reject(error.toString());
});
});
}
const saveAs = (blob, filename) => {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
const body = document.querySelector('body');
const file = new Blob([blob], {type: 'application/json'});
link.href = window.URL.createObjectURL(file); // 创建对象url
link.download = filename;
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
// 通过调用 URL.createObjectURL() 创建的 URL 对象
window.URL.revokeObjectURL(link.href);
}
}
getFile(url).then((blob) => {
saveAs(blob, filename);
});