fix bug
This commit is contained in:
76
src/utils/import-excel.js
Normal file
76
src/utils/import-excel.js
Normal file
@@ -0,0 +1,76 @@
|
||||
import { importBlob } from '@/api/common';
|
||||
import { downloadXls } from '@/utils/util';
|
||||
import NProgress from 'nprogress';
|
||||
import 'nprogress/nprogress.css';
|
||||
|
||||
const excelPattern = /\.(xls|xlsx)$/;
|
||||
|
||||
const isExcelResponse = res => {
|
||||
const contentType = res.headers['content-type'] || res.data.type || '';
|
||||
return contentType.includes('application/vnd.ms-excel');
|
||||
};
|
||||
|
||||
const parseBlobJson = async blob => {
|
||||
const text = await blob.text();
|
||||
return text ? JSON.parse(text) : {};
|
||||
};
|
||||
|
||||
export const openImportDialog = (vm, businessName, onSuccess) => {
|
||||
const column = vm.findColumn(vm.excelOption.column, 'excelFile');
|
||||
column.httpRequest = (option, uploadColumn) =>
|
||||
handleImportExcel(vm, option, uploadColumn, businessName, onSuccess);
|
||||
vm.excelBox = true;
|
||||
};
|
||||
|
||||
export const handleImportExcel = async (vm, option, column, businessName, onSuccess) => {
|
||||
const file = option.file;
|
||||
const fileName = file && file.name ? file.name.toLowerCase() : '';
|
||||
if (!excelPattern.test(fileName)) {
|
||||
vm.$message.error('请上传 .xls,.xlsx 标准格式文件');
|
||||
if (typeof option.onError === 'function') {
|
||||
option.onError(new Error('请上传 .xls,.xlsx 标准格式文件'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
NProgress.start();
|
||||
try {
|
||||
const res = await importBlob(column.action, file);
|
||||
if (isExcelResponse(res)) {
|
||||
downloadXls(
|
||||
res.data,
|
||||
`${businessName}导入失败明细${vm.$dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`
|
||||
);
|
||||
vm.$message.warning('部分数据导入失败,已下载失败明细');
|
||||
} else {
|
||||
const result = await parseBlobJson(res.data);
|
||||
if (result.code !== 200) {
|
||||
vm.$message.error(result.msg || '导入失败');
|
||||
if (typeof option.onError === 'function') {
|
||||
option.onError(new Error(result.msg || '导入失败'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
vm.$message.success(result.msg || '导入数据成功');
|
||||
}
|
||||
vm.excelBox = false;
|
||||
vm.excelForm = {};
|
||||
if (typeof onSuccess === 'function') {
|
||||
onSuccess();
|
||||
} else if (typeof vm.onLoad === 'function') {
|
||||
vm.onLoad(vm.page, vm.query);
|
||||
} else if (typeof vm.initTree === 'function') {
|
||||
vm.initTree();
|
||||
}
|
||||
if (typeof option.onSuccess === 'function') {
|
||||
option.onSuccess(res);
|
||||
}
|
||||
} catch (error) {
|
||||
vm.$message.error(error.message || '导入失败');
|
||||
if (typeof option.onError === 'function') {
|
||||
option.onError(error);
|
||||
}
|
||||
} finally {
|
||||
NProgress.done();
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user