文件上传之后(文件信息暂存在前端,还未上传到后端),如修改原文件名,然后点击上传,会导致上传失败。所以在上传到后端之前需要校验文件。
校验方法:
export const checkFile = (file: any) => {
return new Promise(resolve => {
const reader: any = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onerror = () => {
// read error caught here
resolve({ success: false, msg: '文件发生变化请重新上传' });
};
reader.onload = () => {
resolve({ success: true, msg: '' });
};
});
};
使用:
async uploadImportUser(option: any) {
this.saveLoading = true;
try {
// 校验文件
const checkFileResult: any = await checkFile(option.file);
if (!checkFileResult.success) {
this.$message.error(checkFileResult.msg);
this.fileList = [];
this.saveLoading = false;
return;
}
const params = {
templateFile: option.file,
resourceTreeId: this.currentNode.id,
};
const { data, msg }: any = await apiSaveTreeBatchRelateImportUser(params);
this.saveLoading = false;
let confirmText: string = msg && msg !== 'Network Error' ? msg : '文件有误,请重新上传';
if (data?.summaryMsg) {
confirmText = `<div><b>${data.summaryMsg || ''}</b><br><br>`;
if (data.errMsgList?.length) {
confirmText += `<p>${data.errMsgList.join('<br>')}</p>`;
}
confirmText += '</div>';
}
this.$confirm(confirmText, '提示', {
confirmButtonText: '确认',
showCancelButton: false,
closeOnClickModal: false,
closeOnPressEscape: false,
dangerouslyUseHTMLString: true,
customClass: 'upload-import-user-result-confirm',
})
.then(() => {})
.catch(() => {})
.finally(() => {
this.close(false);
});
} catch (error) {
console.log('上传导入失败:', error);
this.showAlert('导入失败!');
this.saveLoading = false;
this.close(true);
}
}