提交 d8e29d2d 编写于 作者: fzh's avatar fzh

update: 修改限制文件上传类型

上级 9fbb2bc9
<template> <template>
<div class="app-file-upload"> <div class="app-file-upload">
<el-row> <el-row>
<el-col v-if="rowPreview && files.length > 0" :span="12" class="upload-col"> <el-col v-if="rowPreview && files.length > 0" :span="12" class="upload-col">
<el-button size='small' class="button-preview" icon='el-icon-view' :disabled="disabled" @click="()=>{this.dialogVisible = true;}">{{$t('components.appFileUpload.preview')}}<Badge :count="files.length" type="info"></Badge></el-button> <el-button size='small' class="button-preview" icon='el-icon-view' :disabled="disabled" @click="()=>{this.dialogVisible = true;}">{{$t('components.appFileUpload.preview')}}<Badge :count="files.length" type="info"></Badge></el-button>
</el-col> </el-col>
<el-col :span="(rowPreview && files.length > 0) ? 12 : 24" class="upload-col"> <el-col :span="(rowPreview && files.length > 0) ? 12 : 24" class="upload-col">
<el-upload <el-upload
:disabled="disabled" :disabled="disabled"
:file-list="files" :file-list="files"
:action="uploadUrl" :action="getAction()"
:limit="multiple ? limit: 1" :headers="myHeaders"
:accept="accept" :before-upload="beforeUpload"
:multiple="multiple" :before-remove="onRemove"
:headers="{}" :on-success="onSuccess"
:before-upload="beforeUpload" :on-error="onError"
:before-remove="onRemove" :on-preview="onDownload"
:on-success="onSuccess" :drag="isdrag"
:on-error="onError" :show-file-list="!rowPreview"
:on-preview="onDownload" >
:drag="isdrag" <el-button v-if="!isdrag" size='small' icon='el-icon-upload' :disabled="disabled">{{this.$t('app.fileUpload.caption')}}</el-button>
:show-file-list="!rowPreview" <i v-if="isdrag" class="el-icon-upload"></i>
:on-exceed = "handleExceed" <div v-if="isdrag" class="el-upload__text" v-html="$t('components.appFileUpload.uploadText')"></div>
> </el-upload>
<el-button v-if="!isdrag" size='small' icon='el-icon-upload' :disabled="disabled || !(multiple || files.length === 0)">{{this.$t('app.fileUpload.caption')}}</el-button> </el-col>
<i v-if="isdrag" class="el-icon-upload"></i> </el-row>
<div v-if="isdrag" class="el-upload__text" v-html="$t('components.appFileUpload.uploadText')"></div> <modal width="80%" v-model="dialogVisible" footer-hide class-name='upload-preview-modal'>
</el-upload> <ul class="">
</el-col> <li v-for="(file,index) in files" :key="index" class="preview-file-list-item">
</el-row> <div class='preview-file-list-img'>
<modal width="80%" v-model="dialogVisible" footer-hide class-name='upload-preview-modal'> <el-image :src="file.url" class='' style=''>
<ul class=""> <div slot='error' class='image-slot'>
<li v-for="(file,index) in files" :key="index" class="preview-file-list-item"> <img src="/assets/img/picture.png" style='width:100%;height:100%;'>
<div class='preview-file-list-img'> </div>
<el-image :src="file.url" class='' style=''> </el-image>
<div slot='error' class='image-slot'> <div class='preview-file-list-actions' @mouseenter="()=>{showActions = true;}" @mouseleave="()=>{showActions = false;}">
<img src="/assets/img/picture.png" style='width:100%;height:100%;'> <span v-show="showActions" class='action-download'>
</div> <i class='el-icon-download' @click="onDownload(file)"></i>
</el-image> </span>
<div class='preview-file-list-actions' @mouseenter="()=>{showActions = true;}" @mouseleave="()=>{showActions = false;}"> <span v-show="showActions" :style="{ 'display': disabled? 'none' : 'inline-block' }" class='action-delete'>
<span v-show="showActions" class='action-download'> <i class='el-icon-delete' @click="onRemove(file, files)"></i>
<i class='el-icon-download' @click="onDownload(file)"></i> </span>
</span> </div>
<span v-show="showActions" :style="{ 'display': disabled? 'none' : 'inline-block' }" class='action-delete'>
<i class='el-icon-delete' @click="onRemove(file, files)"></i>
</span>
</div> </div>
</div> <div class="file-name">{{file.name}}</div>
<div class="file-name">{{file.name}}</div> </li>
</li> </ul>
</ul> </modal>
</modal> </div>
</div> </template>
</template>
<script lang="ts">
<script lang="ts"> import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'; import { Environment } from '@/environments/environment';
import { Environment } from '@/environments/environment'; import { CreateElement } from 'vue';
import { CreateElement } from 'vue'; import { Subject, Unsubscribable } from 'rxjs';
import { Subject, Unsubscribable } from 'rxjs'; import Axios from 'axios';
import { Message } from 'element-ui';
@Component({
}) @Component({
export default class AppFileUpload extends Vue { })
export default class AppFileUpload extends Vue {
/**
* 表单状态 /**
* * 表单状态
* @type {Subject<any>} *
* @memberof AppFileUpload * @type {Subject<any>}
*/ * @memberof AppFileUpload
@Prop() public formState?: Subject<any> */
@Prop() public formState?: Subject<any>
/**
* 是否忽略表单项书香值变化 /**
* * 是否忽略表单项书香值变化
* @type {boolean} *
* @memberof AppFileUpload * @type {boolean}
*/ * @memberof AppFileUpload
@Prop() public ignorefieldvaluechange?: boolean; */
@Prop() public ignorefieldvaluechange?: boolean;
/**
* 是否支持拖拽 /**
* * 是否支持拖拽
* @type {boolean} *
* @memberof AppFileUpload * @type {boolean}
*/ * @memberof AppFileUpload
@Prop() public isdrag?: boolean; */
@Prop() public isdrag?: boolean;
/**
* 表单状态事件 /**
* * 表单状态事件
* @private *
* @type {(Unsubscribable | undefined)} * @private
* @memberof AppFileUpload * @type {(Unsubscribable | undefined)}
*/ * @memberof AppFileUpload
private formStateEvent: Unsubscribable | undefined; */
private formStateEvent: Unsubscribable | undefined;
/**
* 表单数据 /**
* * 表单数据
* @type {string} *
* @memberof AppFileUpload * @type {string}
*/ * @memberof AppFileUpload
@Prop() public data!: string; */
@Prop() public data!: string;
/**
* 视图参数 /**
* * 视图参数
* @type {*} *
* @memberof AppFormDRUIPart * @type {*}
*/ * @memberof AppFormDRUIPart
@Prop() public viewparams!: any; */
@Prop() public viewparams!: any;
/**
* 视图上下文 /**
* * 视图上下文
* @type {*} *
* @memberof AppAutocomplete * @type {*}
*/ * @memberof AppAutocomplete
@Prop() public context!: any; */
@Prop() public context!: any;
/**
* 初始化值 /**
* * 初始化值
* @type {*} *
* @memberof AppFileUpload * @type {*}
*/ * @memberof AppFileUpload
@Prop() public value?: any; */
@Prop() public value?: any;
/**
* 数据值变化 /**
* * 数据值变化
* @param {*} newval *
* @param {*} val * @param {*} newval
* @memberof AppFileUpload * @param {*} val
*/ * @memberof AppFileUpload
@Watch('value') */
onValueChange(newval: any, val: any) { @Watch('value')
if (this.ignorefieldvaluechange) { onValueChange(newval: any, val: any) {
return; if (this.ignorefieldvaluechange) {
} return;
this.getParams(); }
this.setFiles(newval); this.getParams();
this.dataProcess(); this.setFiles(newval);
} this.dataProcess();
}
/**
* 所属表单项名称 /**
* * 所属表单项名称
* @type {string} *
* @memberof AppFileUpload * @type {string}
*/ * @memberof AppFileUpload
@Prop() public name!: string; */
@Prop() public name!: string;
/**
* 是否禁用 /**
* * 是否禁用
* @type {boolean} *
* @memberof AppFileUpload * @type {boolean}
*/ * @memberof AppFileUpload
@Prop() public disabled?: boolean; */
@Prop() public disabled?: boolean;
/**
* 上传参数 /**
* * 上传参数
* @type {string} *
* @memberof AppFileUpload * @type {string}
*/ * @memberof AppFileUpload
@Prop() public uploadparams?: any; */
@Prop() public uploadparams?: any;
/**
* 下载参数 /**
* * 下载参数
* @type {string} *
* @memberof AppFileUpload * @type {string}
*/ * @memberof AppFileUpload
@Prop() public exportparams?: any; */
@Prop() public exportparams?: any;
/**
* 是否支持多个文件上传 /**
* * 文件列表
* @type {string} *
* @memberof AppFileUpload * @memberof AppFileUpload
*/ */
@Prop({default: true}) public multiple!: boolean; public files = [];
/** /**
* 最大允许上传个数 * 上传params
* *
* @type {*} * @type {Array<any>}
* @memberof AppImageUpload * @memberof AppFileUpload
*/ */
@Prop({default: 9999}) public limit!: number; public upload_params: Array<any> = [];
/** /**
* 接受上传的文件类型 * 导出params
* *
* @type {*} * @type {Array<any>}
* @memberof AppImageUpload * @memberof AppFileUpload
*/ */
@Prop({default: '*'}) public accept!: string; public export_params: Array<any> = [];
/** /**
* 上传文件路径 * 自定义数组
* *
* @memberof AppFileUpload * @type {Array<any>}
*/ * @memberof AppFileUpload
public uploadUrl = Environment.BaseUrl + Environment.UploadFile; */
public custom_arr: Array<any> = [];
/**
* 下载文件路径 /**
* * 应用参数
* @memberof AppFileUpload *
*/ * @type {*}
public downloadUrl = Environment.BaseUrl + Environment.ExportFile; * @memberof AppImageUpload
*/
/** public appData: any;
* 文件列表
* /**
* @memberof AppFileUpload * 文件上传限制类型
*/ *
public files = []; * @type {*}
* @memberof DiskFileUpload
/** */
* 上传params limitType:Array<String> = ['application/x-msdownload','text/x-sh','text/html','text/javascript']
*
* @type {Array<any>} /**
* @memberof AppFileUpload * 当前登陆人的token
*/ *
public upload_params: Array<any> = []; * @type {string}
* @memberof DiskFileUpload
/** */
* 导出params public token: string = "Bearer " + localStorage.getItem('token');
*
* @type {Array<any>} /**
* @memberof AppFileUpload * 上传文件请求头
*/ *
public export_params: Array<any> = []; * @type {*}
* @memberof DiskFileUpload
/** */
* 自定义数组 public myHeaders: any = {Authorization: this.token};
*
* @type {Array<any>} /**
* @memberof AppFileUpload * 拼接上传路径
*/ *
public custom_arr: Array<any> = []; * @memberof DiskFileUpload
*/
/** public getAction() {
* 应用参数 return `${(window as any).Environment.UploadFile}`+ '?ownertype=' + this.name + '&ownerid=' + JSON.parse(this.data).srfkey;
* }
* @type {*} /**
* @memberof AppImageUpload * 设置files
*/ *
public appData: any; * @private
* @memberof AppFileUpload
/** */
* 文件上传限制类型 private setFiles(value:any): void {
* if(value==null){
* @type {*} this.files = [];
* @memberof DiskFileUpload return;
*/ }
limitType:Array<String> = ['application/x-msdownload','text/x-sh','text/html','text/javascript'] let _files = JSON.parse(value);
if (value && Object.prototype.toString.call(_files)=='[object Array]') {
/** this.files = _files;
* 设置files } else {
* this.files = [];
* @private }
* @memberof AppFileUpload }
*/
private setFiles(value:any): void { /**
let _files = JSON.parse(value); * 数据处理
if (value && Object.prototype.toString.call(_files)=='[object Array]') { *
this.files = _files; * @private
} else { * @memberof AppFileUpload
this.files = []; */
} private dataProcess(): void {
} let _url = `${(window as any).Environment.UploadFile}`;
if (this.upload_params.length > 0 ) {
/** _url +='?';
* 数据处理 this.upload_params.forEach((item:any,i:any)=>{
* _url += `${Object.keys(item)[0]}=${Object.values(item)[0]}`;
* @private if(i<this.upload_params.length-1){
* @memberof AppFileUpload _url += '&';
*/ }
private dataProcess(): void { })
}
let _url = `${Environment.BaseUrl}${Environment.UploadFile}`; this.files.forEach((file: any) => {
if (this.upload_params.length > 0 ) { let url = `${(window as any).Environment.ExportFile}/${file.id}`;
_url +='?'; if (this.export_params.length > 0) {
this.upload_params.forEach((item:any,i:any)=>{ url +='?';
_url += `${Object.keys(item)[0]}=${Object.values(item)[0]}`; this.export_params.forEach((item:any,i:any)=>{
if(i<this.upload_params.length-1){ url += `${Object.keys(item)[0]}=${Object.values(item)[0]}`;
_url += '&'; if(i<this.export_params.length-1){
} url += '&';
}) }
} })
}
this.uploadUrl = _url; file.url = url;
});
this.files.forEach((file: any) => { }
let url = `${this.downloadUrl}/${file.id}`;
if (this.export_params.length > 0) {
url +='?';
this.export_params.forEach((item:any,i:any)=>{ /**
url += `${Object.keys(item)[0]}=${Object.values(item)[0]}`; * vue 生命周期
if(i<this.export_params.length-1){ *
url += '&'; * @memberof AppFileUpload
} */
}) public created() {
} if (this.formState) {
file.url = url; this.formStateEvent = this.formState.subscribe(($event: any) => {
}); // 表单加载完成
} if (Object.is($event.type, 'load')) {
this.getParams();
this.setFiles(this.value);
this.dataProcess();
/** }
* vue 生命周期 });
* }
* @memberof AppFileUpload }
*/
public created() { /**
if (this.formState) { * vue 生命周期
this.formStateEvent = this.formState.subscribe(($event: any) => { *
// 表单加载完成 * @returns
if (Object.is($event.type, 'load')) { * @memberof AppFileUpload
this.getParams(); */
this.setFiles(this.value); public mounted() {
this.dataProcess(); this.appData = this.$store.getters.getAppData();
} this.getParams();
}); this.setFiles(this.value);
} this.dataProcess();
} }
/** /**
* vue 生命周期 *获取上传,导出参数
* *
* @returns *@memberof AppFileUpload
* @memberof AppFileUpload */
*/ public getParams(){
public mounted() { let uploadparams: any = JSON.parse(JSON.stringify(this.uploadparams));
this.appData = this.$store.getters.getAppData(); let exportparams: any = JSON.parse(JSON.stringify(this.exportparams));
this.getParams();
this.setFiles(this.value); let upload_params: Array<string> = [];
this.dataProcess(); let export_params: Array<string> = [];
}
let param:any = this.viewparams;
/** let context:any = this.context;
*获取上传,导出参数 let _data:any = JSON.parse(this.data);
*
*@memberof AppFileUpload if (this.uploadparams && !Object.is(this.uploadparams, '')) {
*/ upload_params = this.$util.computedNavData(_data,param,context,uploadparams);
public getParams(){ }
let uploadparams: any = JSON.parse(JSON.stringify(this.uploadparams)); if (this.exportparams && !Object.is(this.exportparams, '')) {
let exportparams: any = JSON.parse(JSON.stringify(this.exportparams)); export_params = this.$util.computedNavData(_data,param,context,exportparams);
}
let upload_params: Array<string> = [];
let export_params: Array<string> = []; this.upload_params = [];
this.export_params = [];
let param:any = this.viewparams;
let context:any = this.context; for (const item in upload_params) {
let _data:any = JSON.parse(this.data); this.upload_params.push({
[item]:upload_params[item]
if (this.uploadparams && !Object.is(this.uploadparams, '')) { })
upload_params = this.$util.computedNavData(_data,param,context,uploadparams); }
} for (const item in export_params) {
if (this.exportparams && !Object.is(this.exportparams, '')) { this.export_params.push({
export_params = this.$util.computedNavData(_data,param,context,exportparams); [item]:export_params[item]
} })
}
this.upload_params = []; }
this.export_params = [];
/**
for (const item in upload_params) { * 组件销毁
this.upload_params.push({ *
[item]:upload_params[item] * @memberof AppFileUpload
}) */
} public destroyed(): void {
for (const item in export_params) { if (this.formStateEvent) {
this.export_params.push({ this.formStateEvent.unsubscribe();
[item]:export_params[item] }
}) }
}
} /**
* 上传之前
/** *
* 组件销毁 * @param {*} file
* * @memberof AppFileUpload
* @memberof AppFileUpload */
*/ public beforeUpload(file: any) {
public destroyed(): void { const blackList = Environment.blackList;
if (this.formStateEvent) { const fileName = file.name?.trim().toLowerCase();
this.formStateEvent.unsubscribe(); if (typeof fileName === 'string' && blackList.some(item => fileName.endsWith(`.${item}`))) {
} Message.error(`不可上传 ${blackList.join('、')}类型的文件!`);
} return false;
}
/** if(this.imageOnly){
* 上传之前 const imageTypes = ["image/jpeg" , "image/gif" , "image/png" , "image/bmp"];
* const isImage = imageTypes.some((type: any)=> Object.is(type, file.type));
* @param {*} file if (!isImage) {
* @memberof AppFileUpload this.$Notice.error({ title: (this.$t('components.appFileUpload.fileTypeErrorTitle') as any) ,desc: (this.$t('components.appFileUpload.fileTypeErrorInfo') as any)});
*/ }
public beforeUpload(file: any) { return isImage;
if(this.limitType.includes(file.type)){ }
Message.error('不可上传 html、js、 exe、sh类型的文件!') }
return false
} /**
if(this.imageOnly){ * 上传成功回调
const imageTypes = ["image/jpeg" , "image/gif" , "image/png" , "image/bmp"]; *
const isImage = imageTypes.some((type: any)=> Object.is(type, file.type)); * @param {*} response
if (!isImage) { * @param {*} file
this.$Notice.error({ title: (this.$t('components.appFileUpload.fileTypeErrorTitle') as any) ,desc: (this.$t('components.appFileUpload.fileTypeErrorInfo') as any)}); * @param {*} fileList
} * @memberof AppFileUpload
return isImage; */
} public onSuccess(response: any, file: any, fileList: any) {
} if (!response) {
return;
/** }
* 上传成功回调 const data = { name: response.filename, id: response.fileid };
* let arr: Array<any> = [];
* @param {*} response this.files.forEach((_file:any) => {
* @param {*} file arr.push({name: _file.name, id: _file.id})
* @param {*} fileList });
* @memberof AppFileUpload arr.push(data);
*/
public onSuccess(response: any, file: any, fileList: any) { let value: any = arr.length > 0 ? JSON.stringify(arr) : null;
if (!response) { this.$emit('formitemvaluechange', { name: this.name, value: value });
return; }
}
const data = { name: response.filename, id: response.fileid }; /**
let arr: Array<any> = []; * 上传失败回调
this.files.forEach((_file:any) => { *
arr.push({name: _file.name, id: _file.id}) * @param {*} error
}); * @param {*} file
arr.push(data); * @param {*} fileList
* @memberof AppFileUpload
let value: any = arr.length > 0 ? JSON.stringify(arr) : null; */
this.$emit('formitemvaluechange', { name: this.name, value: value }); public onError(error: any, file: any, fileList: any) {
} const data = JSON.parse(error.message)
this.$Notice.error({ title: data.message || (this.$t('components.appFileUpload.uploadError') as any)});
/** }
* 上传失败回调
* /**
* @param {*} error * 删除文件
* @param {*} file *
* @param {*} fileList * @param {*} file
* @memberof AppFileUpload * @param {*} fileList
*/ * @memberof AppFileUpload
public onError(error: any, file: any, fileList: any) { */
this.$Notice.error({ title: (this.$t('components.appFileUpload.uploadError') as any) }); public onRemove(file: any, fileList: any) {
} let arr: Array<any> = [];
fileList.forEach((f: any) => {
/** if (f.id != file.id) {
* 删除文件 arr.push({ name: f.name, id: f.id });
* }
* @param {*} file });
* @param {*} fileList let value: any = arr.length > 0 ? JSON.stringify(arr) : null;
* @memberof AppFileUpload if(arr.length == 0){
*/ this.dialogVisible = false;
public onRemove(file: any, fileList: any) { }
let arr: Array<any> = []; this.$emit('formitemvaluechange', { name: this.name, value: value });
fileList.forEach((f: any) => { }
if (f.id != file.id) {
arr.push({ name: f.name, id: f.id }); /**
} * 下载文件
}); *
let value: any = arr.length > 0 ? JSON.stringify(arr) : null; * @param {*} file
if(arr.length == 0){ * @memberof AppFileUpload
this.dialogVisible = false; */
} public onDownload(file: any) {
this.$emit('formitemvaluechange', { name: this.name, value: value }); // 拼接url
} let _this: any = this;
const id = typeof file.id == "string" ? file.id : JSON.stringify(file.id);
/** const name = typeof file.name == "string" ? file.name : JSON.stringify(file.filename);
* 下载文件 const downloadUrl = `${(window as any).Environment.ExportFile}`+ '/' + id + '/' + name;
* // 发送get请求
* @param {*} file Axios.get(downloadUrl, {
* @memberof AppFileUpload responseType: 'arraybuffer',
*/ }).then((response: any) => {
public onDownload(file: any) { if (!response || response.status != 200) {
window.open(file.url); Message.error(_this.$t('components.diskFileUpload.downloadFile') + '!');
} return;
}
/** // 请求成功,后台返回的是一个文件流
* 是否只支持图片上传 if (response.data) {
* // 获取文件名
* @type {boolean} const disposition = response.headers['content-disposition'];
* @memberof AppFileUpload const filename = disposition.split('filename=')[1];
*/ const actualFileName = file.name || filename;
@Prop({default: false}) public imageOnly!: boolean; // 用blob对象获取文件流
let blob = new Blob([response.data], {type: response.headers['content-type']});
/** // 兼容ie语法
* 是否开启行内预览 if('msSaveOrOpenBlob' in navigator){
* window.navigator.msSaveOrOpenBlob(blob, actualFileName);
* @type {boolean} return;
* @memberof AppFileUpload }
*/ // 通过文件流创建下载链接
@Prop({default: false}) public rowPreview!: boolean; var href = URL.createObjectURL(blob);
// 创建一个a元素并设置相关属性
/** let a = document.createElement('a');
* 是否开启行内预览 a.href = href;
* a.download = actualFileName;
* @type {boolean} // 添加a元素到当前网页
* @memberof AppFileUpload document.body.appendChild(a);
*/ // 触发a元素的点击事件,实现下载
public dialogVisible: boolean = false; a.click();
/** // 从当前网页移除a元素
* 是否开启行内预览 document.body.removeChild(a);
* // 释放blob对象
* @type {boolean} URL.revokeObjectURL(href);
* @memberof AppFileUpload } else {
*/ Message.error(_this.$t('components.diskFileUpload.downloadFile1'));
public showActions: boolean = false; }
}).catch((error: any) => {
/** Message.error(_this.$t('components.diskFileUpload.downloadFile') + ':' + error);
* 处理多选超出 });
* }
* @memberof AppFileUpload
*/ /**
public handleExceed(files: any, fileList: any) { * 是否只支持图片上传
this.$message.warning(`${this.$t('components.appFileUpload.limitselect')} ${this.limit}`); *
} * @type {boolean}
* @memberof AppFileUpload
} */
</script> @Prop({default: false}) public imageOnly!: boolean;
<style lang='less'> /**
@import './app-file-upload.less'; * 是否开启行内预览
</style> *
\ No newline at end of file * @type {boolean}
* @memberof AppFileUpload
*/
@Prop({default: false}) public rowPreview!: boolean;
/**
* 是否开启行内预览
*
* @type {boolean}
* @memberof AppFileUpload
*/
public dialogVisible: boolean = false;
/**
* 是否开启行内预览
*
* @type {boolean}
* @memberof AppFileUpload
*/
public showActions: boolean = false;
}
</script>
<style lang='less'>
@import './app-file-upload.less';
</style>
\ No newline at end of file
...@@ -2,85 +2,60 @@ ...@@ -2,85 +2,60 @@
<div id="file-upload"> <div id="file-upload">
<el-row id="el-row"> <el-row id="el-row">
<!--拖拽上传--> <!--拖拽上传-->
<el-col v-if="showDrag==true" class="withDrag"> <el-col v-if="showDrag == true" class="withDrag">
<el-upload <el-upload v-if="!disabled" ref="upload" drag multiple list-type="text" :before-upload="beforeUploadLimit"
ref="upload" :disabled="disabled" :action="getAction()" :headers="myHeaders" :file-list="uploadFileList"
drag :show-file-list="false" :on-error="onError" :on-success="onSuccess">
multiple
list-type="text"
:disabled="disabled"
:action="getAction()"
:headers="myHeaders"
:before-upload="beforeUpload"
:file-list="uploadFileList"
:show-file-list="false"
:http-request="customUploadFile">
<div> <div>
<i class="el-icon-upload"></i> <i class="el-icon-upload"></i>
<div> <div>
<span>{{$t('components.diskFileUpload.fileDrag')}}</span> <span>{{ $t('components.diskFileUpload.fileDrag') }}</span>
<span style="color:#409EFF;">{{$t('components.diskFileUpload.clickUpload')}}</span> <span style="color:#409EFF;">{{ $t('components.diskFileUpload.clickUpload') }}</span>
</div> </div>
</div> </div>
</el-upload> </el-upload>
</el-col> </el-col>
<!--点击上传--> <!--点击上传-->
<el-col v-else class="withoutDrag"> <el-col v-else class="withoutDrag">
<el-upload <el-upload v-if="!disabled" ref="upload" multiple list-type="text" :before-upload="beforeUploadLimit"
ref="upload" :disabled="disabled" :action="getAction()" :headers="myHeaders" :file-list="uploadFileList"
multiple :show-file-list="false" :on-error="onError" :on-success="onSuccess">
list-type="text" <el-button type="primary" size="small" icon="el-icon-upload">
:disabled="disabled" {{ $t('components.diskFileUpload.clickUpload') }}
:action="getAction()"
:headers="myHeaders"
:before-upload="beforeUpload"
:file-list="uploadFileList"
:show-file-list="false"
:http-request="customUploadFile">
<el-button type="primary" size="small" icon="el-icon-upload" :disabled="disabled">
{{$t('components.diskFileUpload.clickUpload')}}
</el-button> </el-button>
</el-upload> </el-upload>
</el-col> </el-col>
<!--文件操作--> <!--文件操作-->
<el-col v-for="(item,index) in uploadFileList" :key="index" class="fileList"> <el-col v-for="(item, index) in uploadFileList" :key="index" class="fileList">
<div class="fileTitle"> <div class="fileTitle">
<i class="el-icon-document"></i> <i class="el-icon-document"></i>
<span>{{item.name}}</span> <span>{{ item.name }}</span>
</div> </div>
<div class="fileMain"> <div class="fileMain">
<el-link type="success" icon="el-icon-download" @click="onDownload(item)"> <el-link type="success" v-show="showDownload" icon="el-icon-download" @click="onDownload(item)">
{{$t('components.diskFileUpload.load')}} {{ $t('components.diskFileUpload.load') }}
</el-link> </el-link>
<el-link type="warning" icon="el-icon-view" v-show="showPreview" @click="onPreview(item)"> <el-link type="warning" icon="el-icon-view" v-show="showPreview" @click="onPreview(item)">
{{$t('components.diskFileUpload.preview')}} {{ $t('components.diskFileUpload.preview') }}
</el-link> </el-link>
<el-link type="primary" icon="el-icon-edit" <el-link type="primary" icon="el-icon-edit"
v-show="showEdit && (item.name.match(/^.+\.(doc|DOC|docx|DOCX|wps|WPS|xls|XLS|xlsx|XLSX|ppt|PPT|et|ET)$/))" v-show="showEdit && (item.name.match(/^.+\.(doc|DOC|docx|DOCX|wps|WPS|xls|XLS|xlsx|XLSX|ppt|PPT|et|ET)$/))"
@click="onEdit(item)">{{$t('components.diskFileUpload.edit')}} @click="onEdit(item)">{{ $t('components.diskFileUpload.edit') }}
</el-link> </el-link>
<el-link icon="el-icon-camera" <el-link icon="el-icon-camera"
v-show="showOcrview && (item.name.match(/^.+\.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|bmp|BMP|pdf|PDF)$/))" v-show="showOcrview && (item.name.match(/^.+\.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|bmp|BMP|pdf|PDF)$/))"
@click="onOcr(item)">OCR @click="onOcr(item)">OCR
</el-link> </el-link>
<el-link type="danger" icon="el-icon-delete" @click="onRemove(item,index)"> <el-link type="danger" v-show="showDelete" icon="el-icon-delete" @click="onRemove(item, index)">
{{$t('components.diskFileUpload.delete')}} {{ $t('components.diskFileUpload.delete') }}
</el-link> </el-link>
</div> </div>
</el-col> </el-col>
</el-row> </el-row>
<!-- 自定义弹框 --> <!-- 自定义弹框 -->
<div class="dialogDiv"> <div class="dialogDiv">
<el-dialog <el-dialog :title="dialogTitle" center width="70%" top="5vh" :visible="showDialog" :close-on-click-modal="true"
:title="dialogTitle" :show-close="true" :before-close="dialogClose" :modal-append-to-body="false">
center
width="70%"
top="5vh"
:visible="showDialog"
:close-on-click-modal="true"
:show-close="true"
:before-close="dialogClose"
:modal-append-to-body="false">
<div style="height: 100%;"> <div style="height: 100%;">
<iframe id="fileIframe" :src="iframeUrl" frameborder="0" width="100%"></iframe> <iframe id="fileIframe" :src="iframeUrl" frameborder="0" width="100%"></iframe>
</div> </div>
...@@ -90,647 +65,717 @@ ...@@ -90,647 +65,717 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import {Component, Vue, Prop, Watch} from 'vue-property-decorator'; import { Component, Vue, Prop } from 'vue-property-decorator';
import {Button, Row, Col, Link, Icon, Upload, Message, MessageBox} from 'element-ui'; import { Message, MessageBox } from 'element-ui';
import Axios from 'axios'; import Axios from 'axios';
import {Subject, Unsubscribable} from 'rxjs'; import { Unsubscribable } from 'rxjs';
import { Environment } from '@/environments/environment';
@Component({}) import { encode } from "js-base64";
export default class DiskFileUpload extends Vue {
@Component({})
/** export default class DiskFileUpload extends Vue {
* 当前表单对象
* /**
* @type {*} * 当前表单对象
* @memberof DiskFileUpload *
*/ * @type {*}
@Prop() public data!: any; * @memberof DiskFileUpload
*/
/** @Prop() public data!: any;
* 当前属性名
* /**
* @type {string} * 当前属性名
* @memberof DiskFileUpload *
*/ * @type {string}
@Prop() public formItemName!: string; * @memberof DiskFileUpload
*/
/** @Prop() public formItemName!: string;
* 当前属性值
* /**
* @type {string} * 当前属性值
* @memberof DiskFileUpload *
*/ * @type {string}
@Prop() public value!: string; * @memberof DiskFileUpload
*/
/** @Prop() public value!: string;
* 当前表单状态
* /**
* @type {*} * 当前表单状态
* @memberof DiskFileUpload *
*/ * @type {*}
@Prop() public formState!: any; * @memberof DiskFileUpload
*/
/** @Prop() public formState!: any;
* 默认为当前实体名称,有指定则按表单参数
* /**
* @type {string} * 默认为当前实体名称,有指定则按表单参数
* @memberof DiskFileUpload *
*/ * @type {string}
@Prop() public folder!: string; * @memberof DiskFileUpload
*/
/** @Prop() public folder!: string;
* 默认为当前实体主键id,有指定则按表单参数
* /**
* @type {string} * 默认为当前实体主键id,有指定则按表单参数
* @memberof DiskFileUpload *
*/ * @type {string}
@Prop() public ownerid!: string; * @memberof DiskFileUpload
*/
/** @Prop() public ownerid!: string;
* 默认为当前属性名,有指定则按表单参数
* /**
* @type {string} * 默认为当前属性名,有指定则按表单参数
* @memberof DiskFileUpload *
*/ * @type {string}
@Prop() public ownertype!: string; * @memberof DiskFileUpload
*/
/** @Prop() public ownertype!: string;
* 持久化
* /**
* @type {boolean} * 持久化
* @memberof DiskFileUpload *
*/ * @type {boolean}
@Prop({default: false}) public persistence?: boolean; * @memberof DiskFileUpload
*/
/** @Prop({ default: false }) public persistence?: boolean;
* 是否启用
* /**
* @type {boolean} * 是否启用
* @memberof DiskFileUpload *
*/ * @type {boolean}
@Prop({default: false}) public disabled?: boolean; * @memberof DiskFileUpload
*/
/** @Prop({ default: false }) public disabled?: boolean;
* 是否显示拖拽区域
* /**
* @type {boolean} * 是否显示拖拽区域
* @memberof DiskFileUpload *
*/ * @type {boolean}
@Prop({default: false}) public showDrag?: boolean; * @memberof DiskFileUpload
*/
/** @Prop({ default: false }) public showDrag?: boolean;
* 是否显示预览按钮
* /**
* @type {boolean} * 是否显示删除按钮
* @memberof DiskFileUpload *
*/ * @type {boolean}
@Prop({default: false}) public showPreview?: boolean; * @memberof DiskFileUpload
*/
/** @Prop({ default: false }) public showDownload?: boolean;
* 是否显示在线编辑按钮
* /**
* @type {boolean} * 是否显示删除按钮
* @memberof DiskFileUpload *
*/ * @type {boolean}
@Prop({default: false}) public showEdit?: boolean; * @memberof DiskFileUpload
*/
/** @Prop({ default: false }) public showDelete?: boolean;
* 是否显示OCR按钮
* /**
* @type {boolean} * 是否显示按钮
* @memberof DiskFileUpload *
*/ * @type {boolean}
@Prop({default: false}) public showOcrview?: boolean; * @memberof DiskFileUpload
*/
/** @Prop({ default: false }) public showPreview?: boolean;
* 表单是否处于编辑状态(有真实主键,srfuf='1';srfuf='0'时处于新建未保存)
* /**
* @type {string} * 是否显示在线编辑按钮
* @memberof DiskFileUpload *
*/ * @type {boolean}
public srfuf: string = '0'; * @memberof DiskFileUpload
*/
@Prop({ default: false }) public showEdit?: boolean;
/**
* 文件列表 /**
* * 是否显示OCR按钮
* @type {Array<any>} *
* @memberof DiskFileUpload * @type {boolean}
*/ * @memberof DiskFileUpload
public uploadFileList: Array<any> = []; */
@Prop({ default: false }) public showOcrview?: boolean;
/**
* 当前登陆人的token /**
* * 表单是否处于编辑状态(有真实主键,srfuf='1';srfuf='0'时处于新建未保存)
* @type {string} *
* @memberof DiskFileUpload * @type {string}
*/ * @memberof DiskFileUpload
public token: string = "Bearer " + localStorage.getItem('token'); */
public srfuf: string = '0';
/**
* 上传文件请求头
* /**
* @type {*} * 文件列表
* @memberof DiskFileUpload *
*/ * @type {Array<any>}
public myHeaders: any = {Authorization: this.token}; * @memberof DiskFileUpload
*/
/** public uploadFileList: Array<any> = [];
* 表单状态事件
* /**
* @type {*} * 当前登陆人的token
* @memberof DiskFileUpload *
*/ * @type {string}
public formStateEvent: any | Unsubscribable | undefined; * @memberof DiskFileUpload
*/
/** public token: string = "Bearer " + localStorage.getItem('token');
* 批量更新标识,false为不更新,true才可以更新
* /**
* @type {boolean} * 上传文件请求头
* @memberof DiskFileUpload *
*/ * @type {*}
public isUpdateBatch: boolean = true; * @memberof DiskFileUpload
*/
/** public myHeaders: any = { Authorization: this.token };
* 新建状态标识,true为新建,false为编辑
* /**
* @type {boolean} * 表单状态事件
* @memberof DiskFileUpload *
*/ * @type {*}
public isCreate: boolean = true; * @memberof DiskFileUpload
*/
/** public formStateEvent: any | Unsubscribable | undefined;
* 自定义弹框标题
* /**
* @type {*} * 批量更新标识,false为不更新,true才可以更新
* @memberof DiskFileUpload *
*/ * @type {boolean}
public dialogTitle: any = ''; * @memberof DiskFileUpload
*/
/** public isUpdateBatch: boolean = true;
* 是否显示自定义弹框
* /**
* @type {boolean} * 新建状态标识,true为新建,false为编辑
* @memberof DiskFileUpload *
*/ * @type {boolean}
public showDialog: boolean = false; * @memberof DiskFileUpload
*/
/** public isCreate: boolean = true;
* 嵌入自定义弹框中iframe的url
* /**
* @type {*} * 自定义弹框标题
* @memberof DiskFileUpload *
*/ * @type {*}
public iframeUrl: any = ''; * @memberof DiskFileUpload
*/
/** public dialogTitle: any = '';
* 文件上传限制类型
* /**
* @type {*} * 是否显示自定义弹框
* @memberof DiskFileUpload *
*/ * @type {boolean}
limitType:Array<String> = ['application/x-msdownload','text/x-sh','text/html','text/javascript'] * @memberof DiskFileUpload
*/
/** public showDialog: boolean = false;
* 关闭自定义弹框
* /**
* @memberof DiskFileUpload * 嵌入自定义弹框中iframe的url
*/ *
public dialogClose() { * @type {*}
this.dialogTitle = ''; * @memberof DiskFileUpload
this.showDialog = false; */
this.iframeUrl = ''; public iframeUrl: any = '';
let iframe: any = document.getElementById("fileIframe");
iframe.parentNode.removeChild("fileIframe"); /**
} * 关闭自定义弹框
*
* @memberof DiskFileUpload
*/
public dialogClose() {
this.dialogTitle = '';
this.showDialog = false;
this.iframeUrl = '';
let iframe: any = document.getElementById("fileIframe");
iframe.parentNode.removeChild("fileIframe");
}
/** /**
* 拼接上传路径 * 文件上传限制类型
* *
* @memberof DiskFileUpload * @type {*}
*/ * @memberof DiskFileUpload
public getAction() { */
return '/net-disk/upload/' + this.getFolder() + '?ownertype=' + this.getOwnertype() + '&ownerid=' + this.getOwnerid(); limitType: Array<String> = ['application/x-msdownload', 'text/x-sh', 'text/html', 'text/javascript']
}
/**
* 拼接上传路径
*
* @memberof DiskFileUpload
*/
public getAction() {
return '/net-disk/upload/' + this.getFolder() + '?ownertype=' + this.getOwnertype() + '&ownerid=' + this.getOwnerid();
}
/** /**
* return folder * return folder
* *
* @memberof DiskFileUpload * @memberof DiskFileUpload
*/ */
public getFolder() { public getFolder() {
return typeof this.folder == "string" ? this.folder : JSON.stringify(this.folder); return typeof this.folder == "string" ? this.folder : JSON.stringify(this.folder);
} }
/** /**
* return ownertype * return ownertype
* *
* @memberof DiskFileUpload * @memberof DiskFileUpload
*/ */
public getOwnertype() { public getOwnertype() {
return typeof this.ownertype == "string" ? this.ownertype : JSON.stringify(this.ownertype); return typeof this.ownertype == "string" ? this.ownertype : JSON.stringify(this.ownertype);
} }
/** /**
* return ownerid * return ownerid
* *
* @memberof DiskFileUpload * @memberof DiskFileUpload
*/ */
public getOwnerid() { public getOwnerid() {
return typeof this.ownerid == "string" ? this.ownerid : JSON.stringify(this.ownerid); return typeof this.ownerid == "string" ? this.ownerid : JSON.stringify(this.ownerid);
} }
/** /**
* vue创建 * vue创建
* *
* @memberof DiskFileUpload * @memberof DiskFileUpload
*/ */
public created() { public created() {
this.formStateEvent = this.formState.subscribe(($event: any) => { this.formStateEvent = this.formState.subscribe(($event: any) => {
// 表单加载完成 // 表单加载完成
if (Object.is($event.type, 'load')) { if (Object.is($event.type, 'load')) {
const data = JSON.parse(JSON.stringify($event.data)); const data = JSON.parse(JSON.stringify($event.data));
// 编辑表单,保存时不进行批量更新 // 编辑表单,保存时不进行批量更新
if (data.srfuf == '1') { if (data.srfuf == '1') {
this.isCreate = false; this.isCreate = false;
this.isUpdateBatch = false; this.isUpdateBatch = false;
} }
// 当persistence = true时 // 当persistence = true时
if (this.persistence == true) { if (this.persistence == true) {
// 直接从表单的data数据里获取当前属性的值 // 直接从表单的data数据里获取当前属性的值
if (data[this.formItemName] && this.uploadFileList.length == 0) { if (data[this.formItemName] && this.uploadFileList.length == 0) {
const files = JSON.parse(data[this.formItemName]); const files = JSON.parse(data[this.formItemName]);
for (let i = 0; i < files.length; i++) { for (let i = 0; i < files.length; i++) {
this.uploadFileList.push(files[i]); this.uploadFileList.push(files[i]);
}
} }
} else {
// 发送get请求获取文件列表
this.getFiles();
} }
} else {
// 发送get请求获取文件列表
this.getFiles();
} }
// 表单保存完成 }
if (Object.is($event.type, 'save')) { // 表单保存完成
// 批量更新文件表中的ownerid if (Object.is($event.type, 'save')) {
if (this.isUpdateBatch == true && this.uploadFileList.length > 0) { // 批量更新文件表中的ownerid
this.updateFileBatch(this.uploadFileList); if (this.isUpdateBatch == true && this.uploadFileList.length > 0) {
} this.updateFileBatch(this.uploadFileList);
} }
}); }
} });
}
/** /**
* 获取文件列表 * 获取文件列表
* *
* @memberof DiskFileUpload * @memberof DiskFileUpload
*/ */
public getFiles() { public getFiles() {
// 拼接url // 拼接url
let _this: any = this; let _this: any = this;
const getUrl = '/net-disk/files/' + this.getFolder(); const getUrl = '/net-disk/files/' + this.getFolder();
// 发送get请求 // 发送get请求
Axios.get(getUrl, { Axios.get(getUrl, {
params: { params: {
ownertype: this.getOwnertype(), ownertype: this.getOwnertype(),
ownerid: this.getOwnerid(), ownerid: this.getOwnerid(),
}, },
}).then((response: any) => { }).then((response: any) => {
if (!response || response.status != 200) { if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.getFileFailure') + '!'); Message.error(_this.$t('components.diskFileUpload.getFileFailure') + '!');
return; return;
} }
// 返回的是一个jsonArray // 返回的是一个jsonArray
if (response.data) { if (response.data) {
const files = JSON.parse(JSON.stringify(response.data)); const files = JSON.parse(JSON.stringify(response.data));
if (this.uploadFileList.length == 0) { if (this.uploadFileList.length == 0) {
this.uploadFileList.push.apply(this.uploadFileList, files); this.uploadFileList.push.apply(this.uploadFileList, files);
}
} }
}).catch((error: any) => { }
Message.error(_this.$t('components.diskFileUpload.getFileFailure') + ':' + error); }).catch((error: any) => {
}); Message.error(_this.$t('components.diskFileUpload.getFileFailure') + ':' + error);
} });
}
/** /**
* 自定义上传文件 * 上传成功回调
* *
* @param 上传文件 * @param {*} response
* @memberof DiskFileUpload * @param {*} file
*/ * @param {*} fileList
public customUploadFile(param: any) { * @memberof AppFileUpload
// 上传的文件 */
let _this: any = this; public onSuccess(response: any, file: any, fileList: any) {
let file = param.file; if (!response) {
// formData传参 return;
let formData = new FormData();
formData.append('file', file);
// 拼接url
const uploadUrl = this.getAction();
// 发送post请求
Axios.post(uploadUrl, formData).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.loadFailure') + '!');
}
// 返回的是一个jsonobject
if (response.data) {
// 新建表单上传,后续需要批量更新操作
if (this.isCreate == true) {
this.isUpdateBatch = true;
}
// 保存到文件列表进行显示
this.uploadFileList.push(response.data);
// persistence=true时需要持久化表单属性
if (this.persistence == true && this.uploadFileList.length > 0) {
const value = JSON.stringify(this.uploadFileList);
this.$emit('formitemvaluechange', {name: this.formItemName, value: value});
}
}
}).catch((error: any) => {
Message.error(_this.$t('components.diskFileUpload.loadFailure') + ':' + error);
})
} }
// 返回的是一个jsonobject
/** // 新建表单上传,后续需要批量更新操作
* 上传之前 if (this.isCreate == true) {
* this.isUpdateBatch = true;
* @param file
* @memberof DiskFileUpload
*/
public beforeUpload(file:any){
if(this.limitType.includes(file.type)){
Message.error('不可上传 html、js、 exe、sh类型的文件!')
return false
}
return true
} }
// 保存到文件列表进行显示
/** this.uploadFileList.push(response);
* 下载文件 // persistence=true时需要持久化表单属性
* if (this.persistence == true && this.uploadFileList.length > 0) {
* @param item 下载文件 const value = JSON.stringify(this.uploadFileList);
* @memberof DiskFileUpload this.$emit('formitemvaluechange', { name: this.formItemName, value: value });
*/
public onDownload(item: any) {
// 拼接url
let _this: any = this;
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.filename);
const downloadUrl = '/net-disk/download/' + this.getFolder() + '/' + id + '/' + name;
// 发送get请求
Axios.get(downloadUrl, {
headers: {
'authcode': item.authcode,
},
responseType: 'arraybuffer',
}).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.downloadFile') + '!');
return;
}
// 请求成功,后台返回的是一个文件流
if (response.data) {
// 获取文件名
const disposition = response.headers['content-disposition'];
const filename = disposition.split('filename=')[1];
// 用blob对象获取文件流
let blob = new Blob([response.data], {type: response.headers['content-type']});
// 通过文件流创建下载链接
var href = URL.createObjectURL(blob);
// 创建一个a元素并设置相关属性
let a = document.createElement('a');
a.href = href;
if (name) {
a.download = name;
} else {
a.download = filename;
}
// 添加a元素到当前网页
document.body.appendChild(a);
// 触发a元素的点击事件,实现下载
a.click();
// 从当前网页移除a元素
document.body.removeChild(a);
// 释放blob对象
URL.revokeObjectURL(href);
} else {
Message.error(_this.$t('components.diskFileUpload.downloadFile1'));
}
}).catch((error: any) => {
Message.error(_this.$t('components.diskFileUpload.downloadFile') + ':' + error);
});
} }
}
/** /**
* 预览文件 * 上传失败回调
* *
* @param item 预览文件 * @param {*} error
* @memberof DiskFileUpload * @param {*} file
*/ * @param {*} fileList
public onPreview(item: any) { * @memberof AppFileUpload
// 拼接url */
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id); public onError(error: any, file: any, fileList: any) {
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name); const data = JSON.parse(error.message)
let previewUrl = '/net-disk/preview/' + this.getFolder() + '/' + id + '/' + name + '?authcode=' + item.authcode; this.$Notice.error({ title: data.message || (this.$t('components.appFileUpload.uploadError') as any) });
Axios.get(previewUrl).then((response: any) => { }
if (!response || response.status != 200) {
return; str2utf8(str: string) {
} const encoder = new TextEncoder();
// 返回一个url,通过自定义弹框打开 const bytes = encoder.encode(str)
if (response.data) { let result = '';
this.dialogTitle = name; for (let i = 0; i < bytes.length; i++) {
this.showDialog = true; result += String.fromCharCode(bytes[i])
this.iframeUrl = response.data;
}
}).catch((error: any) => {
Message.error(error);
});
} }
return result
}
/** /**
* 编辑文件 * 上传之前
* *
* @param item * @param {*} file
* @memberof DiskFileUpload * @memberof AppFileUpload
*/ */
public onEdit(item: any) { beforeUploadLimit(file: any) {
// 拼接url const blackList = Environment.blackList;
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id); const fileName = file.name?.trim().toLowerCase();
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name); if (typeof fileName === 'string' && blackList.some(item => fileName.endsWith(`.${item}`))) {
const editUrl = '/net-disk/editview/' + this.getFolder() + '/' + id + '/' + name + '?authcode=' + item.authcode; Message.error(`不可上传 ${blackList.join('、')}类型的文件!`);
// TODO:暂时用window.open return false;
window.open(editUrl);
} }
return true;
}
/** /**
* ocr识别 * 自定义上传文件
* @param item *
* @memberof DiskFileUpload * @param 上传文件
*/ * @memberof DiskFileUpload
public onOcr(item: any) { */
// 拼接url public customUploadFile(param: any) {
const folder = typeof this.folder == "string" ? this.folder : JSON.stringify(this.folder); // 上传的文件
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id); let _this: any = this;
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name); let file = param.file;
const ocrUrl = '/net-disk/ocrview/' + this.getFolder() + '/' + id + '/' + name + '?authcode=' + item.authcode; // formData传参
Axios.get(ocrUrl).then((response: any) => { let formData = new FormData();
if (!response || response.status != 200) { formData.append('file', file);
return; // 拼接url
const uploadUrl = this.getAction();
// 发送post请求
Axios.post(uploadUrl, formData, { timeout: 6000 }).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.loadFailure') + '!');
}
// 返回的是一个jsonobject
if (response.data) {
// 新建表单上传,后续需要批量更新操作
if (this.isCreate == true) {
this.isUpdateBatch = true;
} }
// 返回一个url,通过自定义弹框打开 // 保存到文件列表进行显示
if (response.data) { this.uploadFileList.push(response.data);
this.dialogTitle = name; // persistence=true时需要持久化表单属性
this.showDialog = true; if (this.persistence == true && this.uploadFileList.length > 0) {
this.iframeUrl = response.data; const value = JSON.stringify(this.uploadFileList);
this.$emit('formitemvaluechange', { name: this.formItemName, value: value });
} }
}).catch((error: any) => {
Message.error(error);
});
}
/**
* 删除文件
*
* @param item
* @param index
* @memberof DiskFileUpload
*/
public onRemove(item: any, index: number) {
let _this: any = this;
if (item) {
MessageBox.confirm(_this.$t('components.diskFileUpload.deleteFile'), _this.$t('components.diskFileUpload.deleteFilePrompt'), {
confirmButtonText: _this.$t('components.diskFileUpload.true'),
cancelButtonText: _this.$t('components.diskFileUpload.false'),
type: 'warning'
}).then(() => {
// 拼接url
const deleteUrl = '/net-disk/files/' + item.id;
// 发送delete请求
Axios.delete(deleteUrl).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.deleteFileFailure') + '!');
}
// 从文件列表中删除
this.uploadFileList.splice(index, 1);
// persistence=true时需要持久化表单属性
if (this.persistence == true) {
const value = JSON.stringify(this.uploadFileList);
this.$emit('formitemvaluechange', {name: this.formItemName, value: value});
}
}).catch((error: any) => {
// 提示删除失败
Message.error(_this.$t('components.diskFileUpload.deleteFileFailure') + ':' + error);
});
});
} }
} }).catch((error: any) => {
Message.error(_this.$t('components.diskFileUpload.loadFailure') + ':' + error);
})
}
/** /**
* 批量更新文件表的ownerid * 下载文件
* *
* @memberof DiskFileUpload * @param item 下载文件
*/ * @memberof DiskFileUpload
public updateFileBatch(files: any) { */
let _this: any = this; public onDownload(item: any) {
// 拼接url // 拼接url
const updateUrl = '/net-disk/files/' + this.getFolder() + '?ownertype=' + this.getOwnertype() + "&ownerid=" + this.getOwnerid(); let _this: any = this;
// requestBody参数 const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
let requestBody = []; const name = typeof item.name == "string" ? item.name : JSON.stringify(item.filename);
if (files) { const downloadUrl = '/ibizutilrpm/download/' + this.getFolder() + '/' + id + '/' + name;
requestBody = files; // 发送get请求
Axios.get(downloadUrl, {
headers: {
'authcode': item.authcode,
},
responseType: 'arraybuffer',
}).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.downloadFile') + '!');
return;
} }
// 发送post请求 // 请求成功,后台返回的是一个文件流
Axios.post(updateUrl, requestBody, { if (response.data) {
headers: { // 获取文件名
"Content-Type": "application/json;charset=UTF-8" const disposition = response.headers['content-disposition'];
}, const filename = disposition.split('filename=')[1];
timeout: 2000 const filenameArr = filename.split('.')
}).then((response: any) => { const itemname = item.name.split('.')
if (!response || response.status != 200) { const docType = '.' + filenameArr[filenameArr.length - 1]
Message.error(_this.$t('components.diskFileUpload.updateFailure') + '!'); itemname.splice(itemname.length - 1, 1, docType)
const actualFileName = itemname.join('');
// 用blob对象获取文件流
let blob = new Blob([response.data], { type: response.headers['content-type'] });
// 兼容ie语法
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(blob, actualFileName);
return; return;
} }
}).catch((error: any) => { // 通过文件流创建下载链接
Message.error(_this.$t('components.diskFileUpload.updateFailure') + ':' + error); var href = URL.createObjectURL(blob);
}); // 创建一个a元素并设置相关属性
} let a = document.createElement('a');
} a.href = href;
</script> a.download = actualFileName;
<style lang="less"> // 添加a元素到当前网页
#file-upload { document.body.appendChild(a);
width: auto; // 触发a元素的点击事件,实现下载
height: auto; a.click();
border: 0px solid black; // 从当前网页移除a元素
document.body.removeChild(a);
// 释放blob对象
URL.revokeObjectURL(href);
} else {
Message.error(_this.$t('components.diskFileUpload.downloadFile1'));
}
}).catch((error: any) => {
Message.error(_this.$t('components.diskFileUpload.downloadFile') + ':' + error);
});
} }
#el-row { /**
border: 0px solid red; * 预览文件
width: 400px; *
* @param item 预览文件
* @memberof DiskFileUpload
*/
public onPreview(item: any) {
// 拼接url
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name);
const downloadUrl = (window as any).Environment.ExportFile + '/' + id + '/' + name;
const previewFileUrl = Environment.previewFileUrl;
if (previewFileUrl) {
const url = encodeURIComponent(encode(`${window.location.origin}${downloadUrl}?fullfilename=${name}`));
this.dialogTitle = name;
this.showDialog = true;
this.iframeUrl = `${previewFileUrl}/onlinePreview?url=${url}`;
}
} }
.withDrag { /**
border: 0px solid grey; * 编辑文件
width: 400px; *
* @param item
* @memberof DiskFileUpload
*/
public onEdit(item: any) {
// 拼接url
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name);
const editUrl = '/net-disk/editview/' + this.getFolder() + '/' + id + '/' + name + '?authcode=' + item.authcode;
// TODO:暂时用window.open
window.open(editUrl);
} }
.withoutDrag { /**
border: 0px solid grey; * ocr识别
width: 400px; * @param item
text-align: left; * @memberof DiskFileUpload
padding-left: 0px; */
padding-top: 0px; public onOcr(item: any) {
margin-top: 0px; // 拼接url
const folder = typeof this.folder == "string" ? this.folder : JSON.stringify(this.folder);
const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name);
const ocrUrl = '/net-disk/ocrview/' + this.getFolder() + '/' + id + '/' + name + '?authcode=' + item.authcode;
Axios.get(ocrUrl).then((response: any) => {
if (!response || response.status != 200) {
return;
}
// 返回一个url,通过自定义弹框打开
if (response.data) {
this.dialogTitle = name;
this.showDialog = true;
this.iframeUrl = response.data;
}
}).catch((error: any) => {
Message.error(error);
});
} }
.fileList { /**
width: 400px; * 删除文件
border: 0px solid grey; *
margin-top: 0px; * @param item
* @param index
* @memberof DiskFileUpload
*/
public onRemove(item: any, index: number) {
let _this: any = this;
if (item) {
MessageBox.confirm(_this.$t('components.diskFileUpload.deleteFile'), _this.$t('components.diskFileUpload.deleteFilePrompt'), {
confirmButtonText: _this.$t('components.diskFileUpload.true'),
cancelButtonText: _this.$t('components.diskFileUpload.false'),
type: 'warning'
}).then(() => {
// 拼接url
const deleteUrl = '/net-disk/files/' + item.id;
// 发送delete请求
Axios.delete(deleteUrl).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.deleteFileFailure') + '!');
}
// 从文件列表中删除
this.uploadFileList.splice(index, 1);
// persistence=true时需要持久化表单属性
if (this.persistence == true) {
const value = this.uploadFileList.length == 0 ? null : JSON.stringify(this.uploadFileList);
this.$emit('formitemvaluechange', { name: this.formItemName, value: value });
}
}).catch((error: any) => {
// 提示删除失败
Message.error(_this.$t('components.diskFileUpload.deleteFileFailure') + ':' + error);
});
});
}
} }
.fileTitle { /**
text-align: left; * 批量更新文件表的ownerid
margin-left: 0px; *
* @memberof DiskFileUpload
*/
public updateFileBatch(files: any) {
let _this: any = this;
// 拼接url
const updateUrl = '/net-disk/files/' + this.getFolder() + '?ownertype=' + this.getOwnertype() + "&ownerid=" + this.getOwnerid();
// requestBody参数
let requestBody = [];
if (files) {
requestBody = files;
}
// 发送post请求
Axios.post(updateUrl, requestBody, {
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
timeout: 2000
}).then((response: any) => {
if (!response || response.status != 200) {
Message.error(_this.$t('components.diskFileUpload.updateFailure') + '!');
return;
}
}).catch((error: any) => {
Message.error(_this.$t('components.diskFileUpload.updateFailure') + ':' + error);
});
} }
}
.fileTitle i { </script>
margin-right: 5px; <style lang="less">
#file-upload {
width: auto;
height: auto;
border: 0px solid black;
}
#el-row {
border: 0px solid red;
width: 400px;
}
.withDrag {
border: 0px solid grey;
width: 400px;
}
.withoutDrag {
border: 0px solid grey;
width: 400px;
text-align: left;
padding-left: 0px;
padding-top: 0px;
margin-top: 0px;
}
.fileList {
width: 400px;
border: 0px solid grey;
margin-top: 0px;
}
.fileTitle {
text-align: left;
margin-left: 0px;
}
.fileTitle i {
margin-right: 5px;
}
.fileMain {
text-align: left;
margin-left: 0px;
margin-top: -10px;
}
.fileMain .el-link:nth-child(n+2) {
margin-left: 10px;
}
.dialogDiv {
// el-dialog头部
.el-dialog__header {
height: 40px;
} }
.fileMain { // el-dialog面板
text-align: left; .el-dialog__wrapper {
margin-left: 0px; height: 90vh;
margin-top: -10px; overflow: visible;
} }
.fileMain .el-link:nth-child(n+2) { // el-dialog
margin-left: 10px; .el-dialog {
height: 100%;
} }
.dialogDiv { // el-dailog内容
// el-dialog头部 .el-dialog__body {
.el-dialog__header { height: inherit;
height: 40px;
}
// el-dialog面板
.el-dialog__wrapper {
height: 90vh;
overflow: visible;
}
// el-dialog
.el-dialog {
height: 100%;
}
// el-dailog内容
.el-dialog__body {
height: inherit;
}
#fileIframe {
height: calc(100% - 40px);
}
} }
#fileIframe {
height: calc(100% - 40px);
}
}
</style> </style>
\ No newline at end of file
export const Environment = {
// 原型示例数模式
SampleMode: false,
// 应用名称
AppName: 'rpm',
// 应用 title
AppTitle: '制度流程管理系统',
// 应用基础路径
BaseUrl: '',
// 系统名称
SysName: 'rpm',
// 远程登录地址,本地开发调试使用
RemoteLogin: '/ibizutil/login',
// 文件导出
ExportFile: '/ibizutil/download',
// 文件上传
UploadFile: '/ibizutil/upload',
// 数据导入单次上传最大数量
sliceUploadCnt: 100,
// 是否为pc端应用
isAppMode:true,
//统一地址
uniteAddress:"http://172.16.100.202:8114",
// 是否为开发模式
devMode: true,
// 是否开启权限认证
enablePermissionValid:false,
// 菜单权限模式,可选值:RT(RT模式),RESOURCE(资源模式),MINIX(混合模式),默认MINIX
menuPermissionMode:"MINIX",
// 项目模板地址
ProjectUrl: "http://demo.ibizlab.cn/ibizr7pfstdtempl/ibizvuer7",
// 打开目标工具,可选参数:sln、mos
debugOpenMode:'mos',
// 配置平台地址
StudioUrl: "http://172.16.170.145/mos/",
// 中心标识
SlnId: "B4BF5C84-D020-4D9A-A986-8FA4FD72816C",
// 系统标识
SysId: "B428B5BE-EA90-4101-A493-BA7085D89F0A",
// 前端应用标识
AppId: "6e0b7357169ef4eba84e1347ed94bd84",
// 项目发布文件地址
PublishProjectUrl: 'http://ibiz.ibizee.cn/t7d01aab0f300e1f75fad0314e98cecab/RPM.git',
// ibiz开放平台地址
ibizlabtUrl: 'https://www.ibizlab.cn',
// ibiz论坛地址
ibizbbstUrl: 'https://bbs.ibizlab.cn',
// 是否启用工作流
workflow: false,
previewFileUrl:'http://172.16.103.143:8013',
blackList: ['html', 'js', 'exe', 'sh', 'bat', 'css', 'htm', 'aspx', 'jsp', 'asp', 'php']
};
// 挂载外部配置文件
if ((window as any).Environment) {
Object.assign(Environment, (window as any).Environment);
}
\ No newline at end of file
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册