提交 2b0193de 编写于 作者: Mosher's avatar Mosher

update:更新导入组件

上级 15327e67
// 导入视图样式 // 导入视图样式
.app-data-upload-view{ .app-data-upload-view{
font-family: "Microsoft YaHei"; font-family: "Microsoft YaHei";
.main-content{ .main-content{
height: 174px; height: calc(100% - 68px);
background: #FAFAFB; background: #FAFAFB;
border-radius: 4px; border-radius: 4px;
border: 1px dashed #D7D7D7; border: 1px dashed #D7D7D7;
// 上传文件区域 margin-top: 10px;
.upload-container{ // 上传文件区域
cursor: pointer; .upload-container{
height: 100%; cursor: pointer;
width: 100%; height: 100%;
text-align: center; width: 100%;
padding-top: 58px; text-align: center;
.icon-import{ padding-top: 58px;
display: block; .icon-import{
margin: 0 auto 17px; display: block;
} margin: 0 auto 17px;
.select-file-text{
height: 17px;
font-size: 12px;
color: #565656;
line-height: 17px;
}
}
// 信息展示容器
.data-info-container{
padding: 8px 10px 6px;
height: 100%;
width: 100%;
// 进度条
.progress{
margin-bottom: 6px ;
.el-progress-bar__outer{
background-color: #FFFFFF;
}
.el-progress-bar__inner{
background-color: #D7E9FF;
}
}
.message-container{
height: 150px;
display: flex;
justify-content: space-between;
ul li{
list-style-type: none;
padding-left: 20px;
}
.result-list{
height: 100%;
width: 100%;
overflow: auto;
}
//成功信息区
.result-list{
ul .success-item{
background: url("~@/assets/img/icon-success.svg") no-repeat 5px 5px;
background-size: 10px 10px;
}
}
//错误信息区
.result-list{
ul .error-item{
background: url("~@/assets/img/icon-error.svg") no-repeat 5px 5px;
background-size: 10px 10px;
}
}
}
}
}
// 下载模板区
.second-content{
padding: 16px 12px 0;
margin-bottom: 30px;
.import-template-message{
font-size: 12px;
height: 17px;
color: #565656;
line-height: 17px;
} }
.import-template{ .select-file-text{
.icon-link{
width: 12px;
margin-bottom: -1px;
margin-right: 3px;
}
height: 17px; height: 17px;
font-size: 12px; font-size: 12px;
color: #57A3FD; color: #565656;
line-height: 17px; line-height: 17px;
} }
} }
// 底部按钮 // 信息展示容器
.button-container{ .data-info-container{
text-align: right; padding: 8px 10px 6px;
margin: 15px; height: 100%;
.el-button{ width: 100%;
margin: 0 0 0 8px; // 进度条
padding: 3px 15px; .progress{
font-size: 12px; margin-bottom: 6px ;
line-height: 20px; .el-progress-bar__outer{
background-color: #FFFFFF;
}
.el-progress-bar__inner{
background-color: #D7E9FF;
}
} }
.primary-button{ .message-container{
color: #FFFFFF; height: 150px;
background-color: #57A3FD; display: flex;
border-color: #57A3FD; justify-content: space-between;
&:hover{ ul li{
background: #66b1ff; list-style-type: none;
border-color: #66b1ff; padding-left: 20px;
} }
&:disabled{ .result-list{
color: var(--button-font-color-light); height: 100%;
border-color: var(--button-font-color-light); width: 100%;
background-color: var(--button-background-color-light); overflow: auto;
} }
//成功信息区
.result-list{
ul .success-item{
background: url("~@/assets/img/icon-success.svg") no-repeat 5px 5px;
background-size: 10px 10px;
}
}
//错误信息区
.result-list{
ul .error-item{
background: url("~@/assets/img/icon-error.svg") no-repeat 5px 5px;
background-size: 10px 10px;
}
}
} }
} }
} }
// 下载模板区
//模态样式 .second-content{
.view-default.app-data-upload-modal{ padding: 16px 12px 0;
.app-data-upload-view{ margin-bottom: 30px;
width: 100%; .import-template-message{
height: 100%; font-size: 12px;
padding: 0 20px 24px 20px; height: 17px;
color: #565656;
line-height: 17px;
} }
.ivu-modal-content .ivu-modal-body{ .import-template{
height: calc(100% - 58px); .icon-link{
width: 12px;
margin-bottom: -1px;
margin-right: 3px;
}
height: 17px;
font-size: 12px;
color: #57A3FD;
line-height: 17px;
} }
// 模态标题 }
.ivu-modal-header{ // 底部按钮
padding: 16px; .button-container{
border: 0; text-align: right;
.ivu-modal-header-inner{ margin: 15px;
color: #333333; height: 28px;
font-weight: 600; .el-button{
height: 24px; margin: 0 0 0 8px;
line-height: 24px; padding: 3px 15px;
font-size: 12px;
line-height: 20px;
}
.primary-button{
color: #FFFFFF;
background-color: #57A3FD;
border-color: #57A3FD;
&:hover{
background: #66b1ff;
border-color: #66b1ff;
}
&:disabled{
color: var(--button-font-color-light);
border-color: var(--button-font-color-light);
background-color: var(--button-background-color-light);
} }
} }
// 关闭图标 }
.ivu-modal-close .ivu-icon-ios-close{ }
color: #999999;
//模态样式
.view-default.app-data-upload-modal{
.app-data-upload-view{
width: 100%;
height: 100%;
padding: 0 20px 24px 20px;
}
.ivu-modal-content .ivu-modal-body{
height: calc(100% - 58px);
}
// 模态标题
.ivu-modal-header{
padding: 16px;
border: 0;
.ivu-modal-header-inner{
color: #333333;
font-weight: 600; font-weight: 600;
height: 24px;
line-height: 24px;
} }
} }
\ No newline at end of file // 关闭图标
.ivu-modal-close .ivu-icon-ios-close{
color: #999999;
font-weight: 600;
}
}
\ No newline at end of file
<template> <template>
<div class="app-data-upload-view" element-loading-background="rgba(57, 57, 57, 0.2)"> <div
class="app-data-upload-view"
v-loading.fullscreen="isUploading"
element-loading-background="rgba(57, 57, 57, 0.2)"
>
<input <input
ref="inputUpLoad" ref="inputUpLoad"
type="file" type="file"
style="display: none" style="display: none"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
@change="fileChange" @change="importFile"
/> />
<div class="main-content"> <div class="main-content">
<div v-if="!selectedFile" class="upload-container" @click="handleUpLoad"> <div v-if="importDataArray.length === 0 && !isUploading && uploadProgress !== 100" class="upload-container" @click="handleUpLoad">
<img class="icon-import" src="@/assets/img/icon-import.svg" /> <img class="icon-import" src="@/assets/img/icon-import.svg" />
<span class="select-file-text">{{ $t('components.appDataUploadView.selectfile') }}</span> <span class="select-file-text">{{ $t("components.appDataUploadView.selectfile") }}</span>
</div> </div>
<div v-else class="data-info-container"> <div class="data-info-container" v-if="importDataArray.length > 0 || isUploading || uploadProgress == 100">
<div v-if="!isUploaded" class="message-container"> <el-progress
<div class="success-list" v-if="!isUploading"> class="progress"
{{ $t('components.appDataUploadView.selectfilesucess') }} v-show="isUploading"
</div> :text-inside="true"
<div class="success-list" v-if="isUploading"> :stroke-width="14"
导入过程中,请稍候 :percentage="uploadProgress"
</div> ></el-progress>
</div> <span class="font-class">{{ promptInfo }}</span>
<div v-else class="message-container">
<div class="result-list" v-if="Object.keys(responseResult).length > 0">
<ul>
<li class="title"><span>{{ $t('components.appDataUploadView.importresult') }}</span></li>
<li>
<span>
{{ $t('components.appDataUploadView.totaldata') }} {{ responseResult.total }} {{ $t('components.appDataUploadView.total') }}{{ $t('app.commonwords.wrong') }}[{{ responseResult.error }}],{{ $t('app.commonwords.success') }}[{{ responseResult.success }}]
</span>
</li>
<template
v-if="responseResult.errorInfos && responseResult.errorInfos.length !== 0">
<li class="title"><span>{{ $t('components.appDataUploadView.errorinfo') }}</span></li>
<li class="error-item" v-for="(item, index) in responseResult.errorInfos" :key="index">
<span v-if="item.index">{{ $t('components.appDataUploadView.start') }} {{item.index}} {{ $t('components.appDataUploadView.row') }}</span><span v-html="item.errorinfo"></span>
</li>
</template>
</ul>
</div>
</div>
</div> </div>
</div> </div>
<el-row class="second-content">
<el-col>
<div class="import-template-message">{{ $t('components.appDataUploadView.datatemplatemessage') }}</div>
<div class="import-template">
<img class="icon-link" src="@/assets/img/icon-link.svg" />
<span style="cursor: pointer" @click="downloadTemp">
{{ viewParams.appDeLogicName + $t('components.appDataUploadView.datatemplate') }}</span
>
</div>
</el-col>
<div class="import-template-download-info" v-if="isUploaded && responseResult.errorfile" @click="downloadFeedbackMsg">
{{ $t('components.appDataUploadView.downloadinfo') }}
</div>
</el-row>
<el-row class="button-container"> <el-row class="button-container">
<el-button type="primary" @click="handleCancel">{{ $t('components.appDataUploadView.cancel') }}</el-button> <el-button type="primary" @click="handleCancel">{{ $t("components.appDataUploadView.cancel") }}</el-button>
<el-button <el-button
:disabled="!selectedFile" :disabled="importDataArray.length === 0"
:loading="isUploading" :loading="isUploading"
type="primary" type="primary"
class="primary-button" class="primary-button"
@click="uploadServer" @click="uploadServer"
>{{ $t('components.appDataUploadView.uploadserver') }}</el-button >{{ $t("components.appDataUploadView.uploadserver") }}</el-button
> >
</el-row> </el-row>
</div> </div>
</template> </template>
<script lang="ts"> <script lang="ts">
import { Environment } from '@/environments/environment'; import XLSX from "xlsx";
import { Util } from '@/utils'; import CodeListService from "@/codelist/codelist-service";
import axios from 'axios'; import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'; import { Environment } from "@/environments/environment";
import moment from "moment";
import { Util } from "@/utils";
@Component({}) @Component({})
export default class AppDataUploadView extends Vue { export default class AppDataUploadView extends Vue {
/**
* 传入视图上下文
*
* @type {string}
* @memberof AppDataUploadView
*/
@Prop() protected viewdata!: string;
@Prop() public viewparam: any; /**
* 传入视图参数
*
* @type {string}
* @memberof AppDataUploadView
*/
@Prop() protected viewparam!: string;
/** /**
* 视图上下文 * 代码表服务对象
* *
* @type {*} * @type {CodeListService}
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
@Prop() public viewdata: any;
public viewParams: any = {}; public codeListService: CodeListService = new CodeListService({ $store: this.$store });
public context: any = {}; /**
* 实体服务对象
*
* @protected
* @type {EntityService}
* @memberof AppDataUploadView
*/
protected entityService: any;
/** /**
* 选择文件数据 * 视图参数
* *
* @type {*} * @type {*}
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public selectedFile: any | null = null; protected viewparams: any = {};
/**
* 导入数据模型
*
* @type {Array<*>}
* @memberof AppDataUploadView
*/
protected importDataModel: Array<any> = [];
/**
* 导入数据集合
*
* @type {Array<*>}
* @memberof AppDataUploadView
*/
public importDataArray: Array<any> = [];
/** /**
* 是否上传完成 * 导入标识
*
* @type {string}
* @memberof AppDataUploadView
*/
protected importId: string = "";
/**
* 是否已有导入数据
* *
* @type {boolean} * @type {boolean}
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public isUploaded: boolean = false; public hasImported: boolean = false;
/** /**
* 上传进度 * 导入数据识别项属性
* *
* @type {number} * @type {string}
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public uploadedProgress: number = 0; public importUniqueItem: string = "";
/** /**
* 是否上传过程中 * 提示信息
*
* @type {string}
* @memberof AppDataUploadView
*/
public promptInfo: string = "";
/**
* 导入状态
* *
* @type {boolean} * @type {boolean}
* @memberof AppDataUploadView * @memberof AppDataUploadView
...@@ -126,12 +150,60 @@ export default class AppDataUploadView extends Vue { ...@@ -126,12 +150,60 @@ export default class AppDataUploadView extends Vue {
public isUploading: boolean = false; public isUploading: boolean = false;
/** /**
* 导入结果集合 * 导入成功数据
* *
* @type {Array<*>} * @type {string}
* @memberof AppDataUploadView
*/
public importSuccessData: Array<any> = [];
/**
* 导入失败数据
*
* @type {string}
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public responseResult: any = {}; public importErrorData: Array<any> = [];
/**
* 读取完成的数据
*
* @type {*}
* @memberof AppDataUploadView
*/
public workBookData: any;
/**
* 所有的代码表
*
* @type {*}
* @memberof AppDataUploadView
*/
public allCodeList: any;
/**
* 属性Map(用作属性转化)
*
* @type {*}
* @memberof AppDataUploadView
*/
public allFieldMap: Map<string, any> = new Map();
/**
* 上传服务器数据切片数
*
* @type {number}
* @memberof AppDataUploadView
*/
public sliceUploadCnt: number = Environment.sliceUploadCnt;
/**
* 上传服务器进度条百分比
*
* @type {number}
* @memberof AppDataUploadView
*/
public uploadProgress: number = 0;
/** /**
* 视图参数变化 * 视图参数变化
...@@ -140,269 +212,357 @@ export default class AppDataUploadView extends Vue { ...@@ -140,269 +212,357 @@ export default class AppDataUploadView extends Vue {
* @param {*} oldVal * @param {*} oldVal
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
@Watch('viewparam', { immediate: true, deep: true }) @Watch("viewparam", { immediate: true, deep: true })
onParamData(newVal: any, oldVal: any) { onParamData(newVal: any, oldVal: any) {
if (newVal) { if (newVal) {
this.viewParams = JSON.parse(newVal); Object.assign(this.viewparams, JSON.parse(this.viewparam));
console.log('视图残花', this.viewParams); this.initBasic();
} }
} }
@Watch('viewdata', { immediate: true, deep: true }) /**
onViewDataChange(newVal: any, oldVal: any) { * 初始化基础数据
if (newVal) { *
this.context = JSON.parse(newVal); * @memberof AppDataUploadView
console.log('上下文', this.context); */
public async initBasic() {
if (this.viewparams.importId) {
this.importId = this.viewparams.importId;
}
if (this.viewparams.importData) {
this.importDataModel = Object.values(this.viewparams.importData);
this.bubbleSort(this.importDataModel, this.importDataModel.length);
}
this.importDataModel.forEach((item: any) => {
if (item.isuniqueitem) {
this.importUniqueItem = item.headername;
}
this.allFieldMap.set(item.headername, item);
});
if (this.viewparams.serviceName) {
this.entityService = await window.entityServiceRegister.getService(this.viewparams.serviceName.toLowerCase());
}
//获取代码表值
this.allCodeList = await this.getChartAllCodeList();
}
/**
* 冒泡排序
*
* @param {*} newVal
* @param {*} oldVal
* @memberof AppDataUploadView
*/
public bubbleSort(array: Array<any>, length: number) {
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
if (array[j].order > array[j + 1].order) {
let temp: any;
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
} }
} }
/**
* 下载导入数据模板
*
* @memberof AppDataUploadView
*/
public downloadTemp() {
this.importExcel(this.viewparams.appDeLogicName + this.$t("components.appDataUploadView.datatemp"), []);
}
/** /**
* 选择文件 * 选择文件
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public handleUpLoad() { public handleUpLoad() {
this.importSuccessData = [];
(this.$refs.inputUpLoad as any).click(); (this.$refs.inputUpLoad as any).click();
} }
/**
* 上传服务器
*
* @memberof AppDataUploadView
*/
public uploadServer() {
if (this.importDataArray.length == 0 || !this.entityService) {
return;
}
let tempDataArray: Array<any> = [];
this.transformData(this.importDataArray, tempDataArray);
this.hasImported = true;
this.isUploading = true;
this.uploadProgress = 0;
this.importDataArray = [];
this.sliceUploadService(tempDataArray, 0);
}
/**
* 数据切片上传
*
* @memberof AppDataUploadView
*/
public sliceUploadService(dataArray: Array<any>, cnt: number) {
if (cnt > dataArray.length) {
this.isUploading = false;
this.uploadProgress = 100;
this.promptInfo = this.$t("components.appDataUploadView.completed") as string;
return;
}
let sliceArray: Array<any> = [];
if (dataArray) {
sliceArray = dataArray.slice(cnt, cnt + this.sliceUploadCnt);
}
try {
this.entityService
.ImportData(this.viewdata, { name: this.importId, importData: sliceArray })
.then((res: any) => {
const result: any = res.data;
if (result && result.rst !== 0) {
this.promptInfo = this.$t("components.appDataUploadView.importfailed") as string;
this.isUploading = false;
return;
}
this.importSuccessData = result.data;
this.promptInfo = this.$t("components.appDataUploadView.completed") as string;
this.uploadProgress = Number(((cnt / dataArray.length) * 100).toFixed(2));
this.sliceUploadService(dataArray, cnt + this.sliceUploadCnt);
})
.catch((error: any) => {
this.isUploading = false;
this.promptInfo = this.$t("components.appDataUploadView.importfailed") as string;
});
} catch (error: any) {
this.isUploading = false;
this.promptInfo = this.$t("components.appDataUploadView.importfailed") as string;
}
}
/** /**
* 取消 * 取消
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public handleCancel() { public handleCancel() {
this.$emit('close', []); this.$emit("close", []);
}
/**
* 导出excel
*
* @memberof AppDataUploadView
*/
public async importExcel(filename: string, _data: any) {
const tHeader: Array<any> = [];
this.importDataModel.forEach((item: any) => {
tHeader.push(item.headername);
});
this.$export.exportExcel().then((excel: any) => {
excel.export_json_to_excel({
header: tHeader, //表头 必填
data: [], //具体数据 必填
filename: filename, //非必填
autoWidth: true, //非必填
bookType: "xlsx", //非必填
});
});
} }
/** /**
* 文件数据变化 * 确认
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public fileChange($event: any) { public handleOK() {
this.$emit("close", this.importSuccessData);
}
/**
* 导入Excel
*
* @memberof AppDataUploadView
*/
public importFile($event: any) {
let obj = $event.target || $event.srcElement; let obj = $event.target || $event.srcElement;
if (!obj.files) { if (!obj.files) {
return; return;
} }
this.selectedFile = obj.files && obj.files.length > 0 ? obj.files[0] : {}; let f = obj.files[0];
let reader = new FileReader();
reader.onload = (e: any) => {
let data = e.target.result;
this.workBookData = XLSX.read(data, { type: "binary", cellDates: true });
let xlsxData = XLSX.utils.sheet_to_json(this.workBookData.Sheets[this.workBookData.SheetNames[0]]);
let list1 = this.getFirstRow(this.workBookData);
xlsxData = this.addXlsxData(xlsxData, list1);
this.importDataArray = Util.deepCopy(xlsxData);
this.promptInfo = `${this.$t('components.appDataUploadView.selectfilesucess')}, ${this.$t('components.appDataUploadView.totaldata')} ${this.importDataArray.length} ${this.$t('components.appDataUploadView.total')}`;
(this.$refs.inputUpLoad as any).value = "";
};
reader.readAsBinaryString(f);
} }
/** /**
* 设置UI状态 * 获取excel第一行的内容
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public setUIState(uploadedProgress: number, isUploading: boolean, isUploaded: boolean, result: any = {}) { public getFirstRow(wb: any) {
this.uploadedProgress = uploadedProgress; //// 读取的excel单元格内容
this.isUploading = isUploading; let wbData = wb.Sheets[wb.SheetNames[0]];
this.isUploaded = isUploaded; // 匹配excel第一行的内容
this.responseResult = result; let re = /^[A-Z]1$/;
let temparr = [];
// excel第一行内容赋值给数组
for (let key in wbData) {
if (wbData.hasOwnProperty(key)) {
if (re.test(key)) {
temparr.push(wbData[key].h);
}
}
}
return temparr;
} }
/** /**
* 下载导入数据模板 * 增加对应字段空白内容
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public downloadTemp() { public addXlsxData(xlsxData: any, list1: any) {
let requestUrl: string = ''; // 空白字段替换值
if (this.viewdata && this.context.srfparentkey && this.context.srfparentdename && this.context.srfparentdename !== this.viewdata.appEntityName) { let addData = null;
requestUrl += `/${Util.srfpluralize(this.viewdata.srfparentdename)}/${this.viewdata.srfparentkey}`; for (let i = 0; i < xlsxData.length; i++) {
} // 要被JSON的数组
requestUrl += `/${Util.srfpluralize(this.viewParams.serviceName)}/importtemplate`; for (let j = 0; j < list1.length; j++) {
if (this.viewParams.importId) { // excel第一行内容
requestUrl += `?srfimporttag=${this.viewParams.importId}`; if (!xlsxData[i][list1[j]]) {
} xlsxData[i][list1[j]] = addData;
axios({ }
url: requestUrl,
method: 'get',
responseType: 'blob',
}).then((response: any) => {
if (response.status == 200) {
let fileName = response.headers['content-disposition']
.split(';')
.find((str: string) => str.indexOf('filename=') != -1)
.slice(9);
fileName = decodeURIComponent(fileName);
let blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
let elink = document.createElement('a');
elink.download = fileName;
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
} }
}); }
return xlsxData;
} }
/** /**
* 下载导入反馈信息 * 获取图表所需代码表
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public downloadFeedbackMsg() { public async getChartAllCodeList() {
if(!this.responseResult || !this.responseResult.errorfile || !this.responseResult.errorfile.fileid){ let codeListMap: Map<string, any> = new Map();
this.$Notice.error({ desc: this.$t('components.appDataUploadView.downloaderror') as string }); if (Object.values(this.importDataModel).length > 0) {
return; await Object.values(this.importDataModel).forEach(async (singleDataModel: any) => {
if (singleDataModel.codelist) {
let tempCodeListMap: Map<any, any> = new Map();
let res: any = await this.getCodeList(singleDataModel.codelist);
if (res && res.length > 0) {
res.forEach((codeListItem: any) => {
tempCodeListMap.set(codeListItem.value, codeListItem.text);
});
}
codeListMap.set(singleDataModel.codelist.tag, tempCodeListMap);
}
});
} }
let downloadUrl: string = `${Environment.ExportFile}/${this.responseResult.errorfile.folder}/${this.responseResult.errorfile.fileid}`; return codeListMap;
const headers = {}; }
axios({
method: 'get', /**
url: downloadUrl, * 获取代码表
headers: headers, *
responseType: 'blob' * @returns {Promise<any>}
}).then((response: any) => { * @memberof AppDataUploadView
if (!response || response.status != 200) { */
this.$Notice.error({ desc: this.$t('components.appDataUploadView.downloaderror') as string }); public getCodeList(codeListObject: any): Promise<any> {
return; return new Promise((resolve: any, reject: any) => {
} if (codeListObject.tag && Object.is(codeListObject.type, "STATIC")) {
// 请求成功,后台返回的是一个文件流 const codelist = this.$store.getters.getCodeList(codeListObject.tag);
if (response.data) { if (codelist) {
// 获取文件名 resolve([...JSON.parse(JSON.stringify(codelist.items))]);
const filename = `导入错误${this.responseResult.errorfile.fileid}.xlsx`; } else {
let filetype = this.calcFilemime('xlsx'); console.log(`----${codeListObject.tag}----${this.$t("app.commonWords.codeNotExist") as string}`);
// 用blob对象获取文件流 }
let blob = new Blob([response.data], { type: filetype }); } else if (codeListObject.tag && Object.is(codeListObject.type, "DYNAMIC")) {
// 通过文件流创建下载链接 this.codeListService
var href = URL.createObjectURL(blob); .getItems(codeListObject.tag)
// 创建一个a元素并设置相关属性 .then((res: any) => {
let a = document.createElement('a'); resolve(res);
a.href = href; })
a.download = filename; .catch((error: any) => {
// 添加a元素到当前网页 console.log(
document.body.appendChild(a); `----${codeListObject.tag}----${this.$t("app.commonWords.codeNotExist") as string}`
// 触发a元素的点击事件,实现下载 );
a.click(); });
// 从当前网页移除a元素
document.body.removeChild(a);
// 释放blob对象
URL.revokeObjectURL(href);
} else {
this.$Notice.error({ desc: this.$t('components.appDataUploadView.downloaderror') as string });
} }
}).catch((error: any) => {
console.error(error);
}); });
} }
/** /**
* 计算文件mime类型 * 转化数据
* *
* @param filetype 文件后缀 * @memberof AppDataUploadView
* @memberof AppDataUploadView */
*/ public transformData(data: Array<any>, result: Array<any>) {
public calcFilemime(filetype: string): string { data.forEach((item: any) => {
let mime = "application/vnd.ms-excel"; let curObject: any = {};
switch (filetype) { Object.keys(item).forEach((ele: any) => {
case ".xlsx": // todo XLSX读取时间为国际时间(东8区)+8H转为标准时间
mime = "application/vnd.ms-excel"; if (item[ele] instanceof Date) {
break; const tempDate: Date = item[ele];
case ".wps": item[ele] = moment(tempDate)
mime = "application/kswps"; .add(8, "h")
break; .format("YYYY-MM-DD HH:mm:ss");
case ".doc": }
mime = "application/msword"; if (this.allFieldMap.get(ele).codelist) {
break; let codelistTag: string = this.allFieldMap.get(ele).codelist.tag;
case ".docx": let codelistIsNumber: boolean = this.allFieldMap.get(ele).codelist.isnumber;
mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; let curCodeList: any = this.transCodeList(codelistTag, codelistIsNumber, true);
break; Object.defineProperty(curObject, this.allFieldMap.get(ele).name, {
case ".txt": value: curCodeList.get(item[ele]),
mime = "text/plain"; writable: true,
break; enumerable: true,
case ".zip": configurable: true,
mime = "application/zip"; });
break; } else {
case ".png": Object.defineProperty(curObject, this.allFieldMap.get(ele).name, {
mime = "image/png"; value: item[ele],
break; writable: true,
case ".gif": enumerable: true,
mime = "image/gif"; configurable: true,
break; });
case ".jpeg": }
mime = "image/jpeg"; });
break; result.push(curObject);
case ".jpg": });
mime = "image/jpeg";
break;
case ".rtf":
mime = "application/rtf";
break;
case ".avi":
mime = "video/x-msvideo";
break;
case ".gz":
mime = "application/x-gzip";
break;
case ".tar":
mime = "application/x-tar";
break;
}
return mime;
} }
/** /**
* 上传服务器 * 翻译代码表
* *
* @memberof AppDataUploadView * @memberof AppDataUploadView
*/ */
public uploadServer() { public transCodeList(codeListTag: string, codelistIsNumber: boolean, isTransform: boolean) {
if (!this.selectedFile) { let curCodeList: any = this.allCodeList.get(codeListTag);
return; if (isTransform) {
} let tempCodelist: Map<string, string> = new Map();
try { curCodeList.forEach((item: string, key: string) => {
let requestUrl: string = ''; let value: any = codelistIsNumber ? Number(key) : key;
this.setUIState(0, true, false); tempCodelist.set(item, value);
if (this.viewdata && this.viewdata.srfparentkey && this.viewdata.srfparentdename) { });
requestUrl += `/${Util.srfpluralize(this.viewdata.srfparentdename)}/${this.viewdata.srfparentkey}`; curCodeList = tempCodelist;
}
requestUrl += `/${Util.srfpluralize(this.viewParams.serviceName)}/importdata2`;
if (this.viewParams.importId) {
requestUrl += `?srfimporttag=${this.viewParams.importId}`;
}
const data = new FormData();
data.append('file', this.selectedFile);
axios
.post(requestUrl, data, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent: any) => {
this.uploadedProgress = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
},
})
.then((res: any) => {
const result: any = {};
if (res && res.status && res.status == 200) {
const { data: data } = res;
const {errorinfo,success,total,errorfile} = data;
result.total = total ? Number(total) : 0;
result.success = success ? Number(success) : 0;
result.errorfile = errorfile;
if(errorinfo && Object.keys(errorinfo).length >0){
result.error = Object.keys(errorinfo).length;
result.errorInfos = [];
Object.keys(errorinfo).forEach((item:any) =>{
result.errorInfos.push({index: Number(item) + 1, errorinfo: errorinfo[item].errorInfo});
})
}
}
this.setUIState(0, false, true, result);
}).catch((error: any) => {
const errorResult: any = {};
if (error && error.status && error.status !== 200) {
errorResult.errorInfos = [];
errorResult.errorInfos.push({ errorInfo: error.data && error.data.message ? error.data.message : '' });
}
this.setUIState(0, false, true, errorResult);
});
} catch (error: any) {
this.setUIState(0, false, true, { errorInfos:[{errorInfo: error.data}] });
} }
return curCodeList;
} }
} }
</script> </script>
<style lang='less'> <style lang="less">
@import './app-data-upload.less'; @import "./app-data-upload.less";
</style> </style>
\ No newline at end of file
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册