模板下载
window.open('模板地址');
上传文件
响应拦截器里判断响应数据是否为文件流
//判断后端返回的是否为文件流
if (response.request.responseType == 'blob') {
//如果后端返回的是文件流,且能获得code值,说明请求失败
if (res.code) {
Message.error(res.message);
} else {
return response;
}
}
<el-upload class="upload-demo" action :before-upload="beforeAvatarUpload" :http-request="uploadFileBtn" :on-success="handleAvatarSuccess" :show-file-list="false" multiple :file-list="fileList">
<el-button type="text" size="small" class="upBtn"></el-button>
<span v-if="this.fileName" class="upLocalCard"></span>
</el-upload>
data() {
return {
fileName: '',
fd: new FormData(),
uploadProgressEvent: '',
dialogVisible: false,
progressPercent: 1, // 进度条默认为0
fileList: [],
};
},
beforeAvatarUpload(file) {
console.log(file);
const isJPG = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
const isLt5M = file.size / 1024 / 1024 < 5;
const fileNameLength = file.name.length < 50;
if (!isJPG) {
this.$message.error('上传文件不符合要求,请重新上传。');
}
if (!isLt5M) {
this.$message.error('上传文件不符合要求,请重新上传。');
}
if (!fileNameLength) {
this.$message.error('上传文件不符合要求,请重新上传。');
}
return isJPG && isLt5M && fileNameLength;
},
uploadFileBtn(item) {
this.progressPercent = 1;
let fd = new FormData();
fd.append('file', item.file);
if (item.file.name) {
this.fileName = item.file.name;
}
// 进度条
const uploadProgressEvent = progressEvent => {
this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total);
};
this.fd = fd;
this.uploadProgressEvent = uploadProgressEvent;
},
submitImport() {
importBusinessList(this.fd, this.uploadProgressEvent).then(res => {
this.progressPercent = 101;
exportExcel(res, '导入结果文件');
this.successRemind = true;
let _this = this;
let timer = setTimeout(function () {
_this.closeVisible();
clearTimeout(timer);
}, 5000);
});
},
//批量导出
export function exportExcel(res, ecxelName) {
const blob = new Blob([res.data]); // 接受文档流
if (!ecxelName) {
ecxelName = Date.now();
}
if ('msSaveOrOpenBlob' in navigator) {
// IE下的导出
window.navigator.msSaveOrOpenBlob(blob, ecxelName + '.xlsx'); // 设置导出的文件名
} else {
// 非ie下的导出
const a = document.createElement('a');
const url = window.URL.createObjectURL(blob);
const filename = ecxelName + '.xlsx'; // 设置导出的文件名
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
}