UploadBase.ts 11.7 KB
import {Component, Emit, Model, Prop, Vue, Watch} from "vue-facing-decorator";
import {AuthenticationManager} from "lib/src/core/security/AuthenticationManager";

@Component({})
export abstract class UploadBase extends Vue {

    /**
     * 请求头设置值
     */
    headers = {Authorization: 'Bearer ' + localStorage.getItem(AuthenticationManager.TOKEN)};

    /**
     * 上传按钮名称
     */
    @Prop({type: String, required: false, default: undefined}) buttonName: string;

    /**
     * 同步 默认异步上传 (待开发)
     */
    @Prop({type: Boolean, required: false, default: false}) sync: boolean;
    /**
     * 上传成功提示语
     */
    @Prop({type: String, required: false, default: undefined})
    uploadSuccessMsg: string;
    /**
     * 上传失败提示语
     */
    @Prop({type: String, required: false, default: undefined})
    uploadErrorMsg: string;
    /**
     * 删除成功提示语
     */
    @Prop({type: String, required: false, default: undefined})
    removeSuccessMsg: string;
    /**
     * 上传文件集合
     */
        // @Prop({type: Array, required: false})
    @Model({required: true, type: Array, name: "fileListProp"})
    fileListProp: any[];
    /**
     * 上传接口
     */
    @Prop({type: String, required: false})
    uploadUrl: string;
    @Prop({type: String, required: false})
    deleteUrl: string;
    /**
     * 最大上传数量
     */
    @Prop({type: Number, required: false, default: 10})
    max: number;
    /**
     * 单位:MB 默认为10MB
     */
    @Prop({type: Number, required: false, default: 10})
    size: number;
    /**
     * 过滤后缀 以,分割
     */
    @Prop({type: String, required: false, default: 'jpg,jpeg,png'})
    suffixes: string;
    /**
     * 选文件时是否可选多个
     */
    @Prop({type: Boolean, required: false, default: false}) multiple: boolean;
    /**
     * 注:使用limit时要开启multiple
     * 多个上传时,一次最大上传数量
     */
    @Prop({type: Number, required: false, default: 1}) limit: number;
    /**
     * 是否展示查看图片的图标
     */
    @Prop({type: Boolean, required: false, default: true}) showPreviewIcon: boolean;
    /**
     * 是否展示删除按钮
     */
    @Prop({type: Boolean, required: false, default: true}) showRemoveIcon: boolean;
    /**
     * 是否展示下载按钮
     */
    @Prop({type: Boolean, required: false, default: true}) showDownloadIcon: boolean;
    /**
     * 是否展示限制的文件类型
     */
    @Prop({type: Boolean, required: false, default: true}) showSuffixes: boolean;
    showSuffixesHint: boolean;
    /**
     * 是否展示限制的文件类型
     */
    @Prop({type: Boolean, required: false, default: true}) showMax: boolean;
    showMaxHint: boolean;
    /**
     * 是否展示上传按钮
     */
    @Prop({type: Boolean, required: false, default: true}) showUploadButton: boolean;
    showButton: boolean;

    /**
     * 查看模式
     */
    @Prop({type: Boolean, required: false, default: false}) viewMode: boolean;

    /**
     * 存储文件位置
     */
    @Prop({type: String, required: true}) directory: string;

    /**
     * 上传接口服务器地址url
     */
    @Prop({type: String, required: false, default: ""}) apiUrl: string;

    /**
     * 文件类型(弹出系统选择框的时候限制选择的文件)
     */
    protected fileType: string;
    /**
     * 组件的文件集合
     */
    protected fileList: any[] = [];

    /**
     * 对外放开的是fileListProp属性,监听fileListProp属性,有新的值后赋值给fileList
     * 为什么要这么做,上传组件的fileList是(受控)的,所以只能组件内容修改他的值,如果从父组件传值
     * 进来修改他的值,就会报错;
     * 如果首次赋值也需要处理则需要添加 {deep: true, immediate: true}
     */
    @Watch('fileListProp', {deep: true, immediate: true})
    onFileListChanged(val: any) {
        if (!val || val.length === 0) {
            this.fileList = [];
            this.showButton = true;
        } else {
            let files = JSON.parse(JSON.stringify(val));
            if (!(files instanceof Array)) {
                files = [files];
            }
            this.fileList = files;
            if (this.fileList.length >= this.max) {
                this.showButton = false;
            }
        }
    }

    abstract showMessage(message: string, type: 'success' | 'warning' | 'error' | 'info');

    /**
     * 获取文件列表
     */
    get fileLists() {
        return this.fileList;
    }

    /**
     * 上传中
     */
    upLoading = false;
    /**
     * 预览可见模态框
     */
    previewVisible = false;


    /**
     * 打开pdf预览
     */
    showPreview = false;

    /**
     * 预览文件
     */
    previewFile: any = null;

    /**
     * 模态框图片
     */
    previewImage: any = null;
    /**
     * 照片墙模式
     * showPreviewIcon 是否展示查看
     * showRemoveIcon 是否展示删除
     * hidePreviewIconInNonImage 上传文件时是否隐藏查看按钮
     */
    @Prop({
        type: Boolean, required: false, default: {
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: true
        }
    })
    showUploadList: any;

    created(): void {
        this.showButton = this.showUploadButton;
        this.showSuffixesHint = this.showSuffixes;
        this.showMaxHint = this.showMax;
        if (this.showUploadList) {
            this.showUploadList.showRemoveIcon = this.showRemoveIcon;
            this.showUploadList.showPreviewIcon = this.showPreviewIcon;
            this.showUploadList.showDownloadIcon = this.showDownloadIcon;
        }

        this.fileType = '.' + this.suffixes.split(',').join(',.');

        if (this.viewMode) {
            this.showButton = false;
            this.showSuffixesHint = false;
            this.showMaxHint = false;
            this.showUploadList.showRemoveIcon = false;
        }
        if (this.fileList.length >= this.max) {
            this.showButton = false;
        }
    }

    //上传接口请求路径
    get action(): string {
        if (this.uploadUrl) {
            return this.uploadUrl + '?directory=' + this.directory;
        } else {
            return 'upload/uploadFile?directory=' + this.directory;
        }
    }

    /**
     * 关闭模态框
     */
    handleCancel() {
        this.previewVisible = false;
    }

    /**
     * 展示图片模态框
     */
    async handlePreview(file: any) {
        this.previewImage = file;
        this.previewVisible = true;
    }

    /**
     * 上传时触发
     */
    handleChange(info: any): void {
        switch (info.file.status) {
            case 'uploading':
                this.upLoading = true;
                break;
            case 'done':
                this.processFiles(info);
                break;
            case 'error':
                this.showMessage(this.uploadErrorMsg || '上传文件发生异常!', 'error');
                this.upLoading = false;
                break;
        }
    }

    /**
     * 处理文件
     */
    processFiles(info: any) {
        let fileList = [...info.fileList];
        fileList = fileList.map(file => {
            if (file.response) {
                file.lastModifiedDate = file.response.lastModifiedDate;
                // file.url = this.listType === 'picture-card' ? file.response.url : '';
                file.url = file.response.url;
                file.uid = file.response.uid;
                file.path = file.response.path;
                file.filePath = file.response.filePath;
                file.fileUrl = file.response.url;
                file.previewPath = file.response.previewPath;
                file.previewUrl = file.response.previewUrl;
                file.generatedFileName = file.response.generatedFileName;
                file.storagePath = file.response.filePath;
            }
            return file;
        });
        this.fileList = fileList;
        this.showMessage(this.uploadSuccessMsg || info.file.name + '上传成功!', 'success');
        this.$emit('update:fileListProp', this.fileList);
        this.$emit('change', this.fileList);
        this.upLoading = false;
    }

    /**
     * 删除时触发
     * 直接删除集合中的数据即可
     * @param file
     */
    handleRemove(file: any) {
        let filePath = '';
        if (file.filePath && file.filePath !== '') {
            filePath = file.filePath;
        } else if (file.response && file.response.filePath && file.response.filePath !== '') {
            filePath = file.response.filePath;
        }
        if (filePath !== '') {
            // @ts-ignore
            this.axios.delete(this.deleteUrl || '' + 'upload/removeFile', {params: {filePath}}).then(() => {
                console.log(filePath);
            });
        }
        const index = this.fileList.indexOf(file);
        this.fileList.splice(index, 1);
        this.$emit('update:fileListProp', this.fileList);
        this.$emit('change', this.fileList);
        this.showMessage(this.removeSuccessMsg || file.name + '删除成功!', 'success');
    }

    download(file: any) {
        this.downloadFile(file.url, file.name);
    }

    preview(file: any) {
        const fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
        this.previewFile = file;
        this.previewFile.fileUrl = file.url;
        this.previewFile.storagePath = file.filePath;
        this.previewFile.fileType = fileType;
        if (fileType !== 'doc' && fileType !== 'docx' && fileType !== 'xls' && fileType !== 'xlsx' && fileType !== 'ppt' && fileType !== 'pptx' && fileType != 'pdf') {
            this.download(file);
        } else {
            this.showPreview = true;
        }
    }

    private downloadFile(url: string, fileName: string) {
        const xhr = new window.XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
            if (xhr.status === 200) {
                const windowUrl = window.URL.createObjectURL(xhr.response);
                const a = document.createElement('a');
                a.href = windowUrl;
                a.download = fileName;
                a.click();
                window.URL.revokeObjectURL(windowUrl);
            }
        };
        xhr.send();
    }


    /**
     * 上传前触发,用于校验格式和,文件大小
     * @param file
     */
    beforeUpload(file: any) {
        if (!this.suffixes) {
            this.suffixes = 'jpg,jpeg,png';
        }
        const isOk = this.suffixes.split(',').some((regex) => file.name.endsWith(regex.toLowerCase()) || file.name.endsWith(regex.toUpperCase()));
        return new Promise((resolve, reject) => {
            try {
                if (this.max !== 1 && this.fileList.length >= this.max) {
                    this.showMessage('最多只能上传' + this.max + '个文件', 'error');
                    reject(file);
                    return;
                }
                if (!isOk) {
                    this.showMessage(`${file.name}文件格式有误!请上传格式为 ${this.suffixes} 的文件!`, 'error');
                    reject(file);
                } else if (!(file.size / 1024 / 1024 < this.size)) {
                    this.showMessage(`上传文件大小必须小于 ${this.size.toString()} MB!`, 'error');
                    // Upload.LIST_IGNORE解决上传失败但是文件还会显示在组建列表的问题
                    // return Upload.LIST_IGNORE;
                    return 'LIST_IGNORE';
                } else {
                    resolve(file);
                }
            } catch (e) {
                console.log(e);
                resolve(file);
            }
        });
    }
}