disk-image-upload.vue 26.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<template>
    <div id="image-upload">
        <el-upload
                ref="imageUpload"
                multiple
                :file-list="imageList"
                list-type="picture-card"
                :action="getAction()"
                :headers="myHeaders"
                :before-upload="beforeUpload"
                :http-request="customImageUpload">
            <i class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file,index}">
                <img class="el-upload-list__item-thumbnail" :src="file.url">
                <span class="el-upload-list__item-actions">
                    <!--预览按钮-->
17 18
                    <span class="el-upload-list__item-preview" @click="onPreview(file)"
                          :title="$t('components.diskImageUpload.preview')"
19 20 21 22
                          v-show="showPreview">
                        <i class="el-icon-view"></i>
                    </span>
                    <!--OCR按钮-->
23 24
                    <span class="el-upload-list__item-delete" @click="onOcr(file)"
                          :title="$t('components.diskImageUpload.OCRdiscern')"
25 26 27 28
                          v-show="showOcrview && (file.name.match(/^.+\.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|bmp|BMP)$/))">
                      <i class="el-icon-camera"></i>
                    </span>
                    <!--下载按钮-->
29 30
                    <span class="el-upload-list__item-delete" @click="onDownload(file)"
                          :title="$t('components.diskImageUpload.load')">
31 32 33
                      <i class="el-icon-download"></i>
                    </span>
                    <!--删除按钮-->
34 35
                    <span class="el-upload-list__item-delete" @click="onRemove(file)"
                          :title="$t('components.diskImageUpload.delete')">
36 37 38 39 40
                      <i class="el-icon-delete"></i>
                    </span>
              </span>
            </div>
        </el-upload>
41
        <!-- 预览弹框 -->
42 43 44
        <el-dialog :visible.sync="dialogVisible" :modal="false">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
45 46 47
        <!-- 自定义弹框 -->
        <div class="dialogDiv">
            <el-dialog
48 49
                    :title="dialogTitle"
                    center
50 51 52 53 54 55 56 57 58 59 60 61
                    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%;">
                    <iframe id="fileIframe" :src="iframeUrl" frameborder="0" width="100%"></iframe>
                </div>
            </el-dialog>
        </div>
62 63 64 65
    </div>
</template>

<script lang="ts">
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
    import {Component, Vue, Prop, Watch} from 'vue-property-decorator';
    import {Message, MessageBox} from 'element-ui';
    import Axios from 'axios';
    import {Subject, Unsubscribable} from 'rxjs';

    @Component({})
    export default class DiskImageUplaod extends Vue {

        /**
         * 当前表单对象
         *
         * @type {*}
         * @memberof DiskImageUplaod
         */
        @Prop() public data!: any;

        /**
         * 当前属性名
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        @Prop() public formItemName!: string;

        /**
         * 当前属性值
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        @Prop() public value!: string;

        /**
         * 当前表单状态
         *
         * @type {*}
         * @memberof DiskImageUplaod
         */
        @Prop() public formState!: any;

        /**
         * 默认为当前实体名称,有指定则按表单参数
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        @Prop() public folder!: string;

        /**
         * 默认为当前实体主键id,有指定则按表单参数
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        @Prop() public ownerid!: string;

        /**
         * 默认为当前属性名,有指定则按表单参数
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        @Prop() public ownertype!: string;

        /**
         * 持久化
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        @Prop({default: false}) public persistence?: boolean;

        /**
         * 是否显示预览按钮
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        @Prop({default: false}) public showPreview?: boolean;


        /**
         * 是否显示OCR按钮
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        @Prop({default: false}) public showOcrview?: boolean;


        /**
         * 表单是否处于编辑状态(有真实主键,srfuf='1';srfuf='0'时处于新建未保存)
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        public srfuf: string = '0';

        /**
         * 图片列表
         *
         * @type {Array<any>}
         * @memberof DiskImageUplaod
         */
        public imageList: Array<any> = [];

        /**
         * 当前登陆人的token
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        public token: string = "Bearer " + localStorage.getItem('token');

        /**
         * 上传文件请求头
         *
         * @type {*}
         * @memberof DiskImageUplaod
         */
        public myHeaders: any = {Authorization: this.token};

        /**
         * 表单状态事件
         *
         * @type {*}
         * @memberof DiskImageUplaod
         */
        public formStateEvent: any | Unsubscribable | undefined;

        /**
         * 批量更新标识,false为不更新,true才可以更新
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        public isUpdateBatch: boolean = true;

        /**
         * 新建状态标识,true为新建,false为编辑
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        public isCreate: boolean = true;

        /**
         * 预览弹出框显示标识,true显示,false隐藏
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        public dialogVisible: boolean = false;

        /**
         * 预览弹出框中的图片地址
         *
         * @type {string}
         * @memberof DiskImageUplaod
         */
        public dialogImageUrl: string = '';

        /**
         * 存放图片的fileid,用于图片列表定位
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
         */
        public imageFileids: Array<any> = [];

236 237 238 239 240 241 242 243
        /**
         * 自定义弹框标题
         *
         * @type {*}
         * @memberof DiskImageUplaod
         */
        public dialogTitle: any = '';

244 245
        /**
         * 是否显示自定义弹框
246 247 248
         *
         * @type {boolean}
         * @memberof DiskImageUplaod
249
         */
250
        public showDialog: boolean = false;
251 252 253

        /**
         * 嵌入自定义弹框中iframe的url
254 255 256
         *
         * @type {*}
         * @memberof DiskImageUplaod
257 258 259 260 261
         */
        public iframeUrl: any = '';

        /**
         * 关闭自定义弹框
262 263
         *
         * @memberof DiskImageUplaod
264 265
         */
        public dialogClose() {
266
            this.dialogTitle = '';
267 268
            this.showDialog = false;
            this.iframeUrl = '';
269
            let iframe: any = document.getElementById("fileIframe");
270 271
            iframe.parentNode.removeChild("fileIframe");
        }
272

273 274 275 276 277 278 279 280
        /**
         * 拼接上传路径
         *
         * @memberof DiskImageUplaod
         */
        public getAction() {
            return '/net-disk/upload/' + this.getFolder() + '?ownertype=' + this.getOwnertype() + '&ownerid=' + this.getOwnerid();
        }
281

282 283 284 285 286 287 288 289
        /**
         * return folder
         *
         * @memberof DiskImageUplaod
         */
        public getFolder() {
            return typeof this.folder == "string" ? this.folder : JSON.stringify(this.folder);
        }
290

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        /**
         * return ownertype
         *
         * @memberof DiskImageUplaod
         */
        public getOwnertype() {
            return typeof this.ownertype == "string" ? this.ownertype : JSON.stringify(this.ownertype);
        }

        /**
         * return ownerid
         *
         * @memberof DiskImageUplaod
         */
        public getOwnerid() {
            return typeof this.ownerid == "string" ? this.ownerid : JSON.stringify(this.ownerid);
        }

        /**
310
         * vue创建
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
         *
         * @memberof DiskImageUplaod
         */
        public created() {
            this.formStateEvent = this.formState.subscribe(($event: any) => {
                // 表单加载完成
                if (Object.is($event.type, 'load')) {
                    const data = JSON.parse(JSON.stringify($event.data));
                    // 编辑表单,保存时不进行批量更新
                    if (data.srfuf == '1') {
                        this.isCreate = false;
                        this.isUpdateBatch = false;
                    }
                    // 当persistence = true时,表单持久化
                    if (this.persistence == true) {
                        // 直接从表单的data数据里获取当前属性的值
                        if (data[this.formItemName] && this.imageList.length == 0) {
                            const files = JSON.parse(data[this.formItemName]);
                            files.forEach((item: any, i: number) => {
                                // 图片列表显示缩略图需要获取真实的图片信息
                                if (item.id && item.name) {
                                    this.getRealImageData(item);
                                }
                            });
                        }
                    } else {
                        // 发送get请求获取图片列表
                        this.getFiles();
                    }
                }
                // 表单保存完成
                if (Object.is($event.type, 'save')) {
                    // 批量更新文件表中的ownerid
                    if (this.isUpdateBatch == true && this.imageList.length > 0) {
                        this.updateFileBatch(this.imageList);
                    }
                }
            });
        }
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        /**
         * 获取图片列表
         *
         * @memberof DiskImageUplaod
         */
        public getFiles() {
            // 拼接url
            let _this: any = this;
            const getUrl = '/net-disk/files/' + this.getFolder();
            // 发送get请求
            Axios.get(getUrl, {
                params: {
                    ownertype: this.getOwnertype(),
                    ownerid: this.getOwnerid(),
                },
366
            }).then((response: any) => {
367 368 369
                if (!response || response.status != 200) {
                    Message.error(_this.$t('components.diskImageUpload.getImageFailure') + "!");
                    return;
370
                }
371 372 373 374
                // 返回的是一个jsonArray
                if (response.data) {
                    const files = JSON.parse(JSON.stringify(response.data));
                    if (this.imageList.length == 0) {
375 376 377 378 379 380 381 382
                        files.forEach((item: any, i: number) => {
                            // 图片列表显示缩略图需要获取真实的图片信息
                            if (item.id && item.name) {
                                this.getRealImageData(item);
                            }
                        });
                    }
                }
383
            }).catch((error: any) => {
384 385 386
                Message.error(_this.$t('components.diskImageUpload.getImageFailure') + ':' + error);
            });
        }
387

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        /**
         * 获取真实的图片信息
         * @param file
         * @memberof DiskImageUplaod
         */
        public getRealImageData(file: any) {
            let fileData = file;
            let _this: any = this;
            // 拼接url,与下载一致
            const downloadUrl = '/net-disk/download/' + this.getFolder() + '/' + fileData.id + '/' + fileData.name;
            // 发送get请求
            Axios.get(downloadUrl, {
                headers: {
                    'authcode': fileData.authcode
                },
                responseType: 'blob',
404 405
            }).then((response: any) => {
                if (!response || response.status != 200) {
406
                    Message.error(_this.$t('components.diskImageUpload.loadImageFailure') + '!');
407
                }
408
                // 请求成功,后台返回的是一个文件流
409
                if (response.data) {
410
                    // 用blob对象获取文件流
411
                    let blob = new Blob([response.data], {type: response.headers['content-type']});
412
                    // 通过文件流创建下载链接
413
                    let href = URL.createObjectURL(blob);
414 415 416 417 418 419 420 421 422 423 424 425 426
                    // 将下载链接保存到图片中
                    fileData.url = href;
                    // 保存图片fileid
                    if (fileData.fileid) {
                        this.imageFileids.push(fileData.fileid);
                    } else if (fileData.id) {
                        this.imageFileids.push(fileData.id);
                    } else {
                        Message.error(_this.$t('components.diskImageUpload.ImageIdNone'));
                        return;
                    }
                    // 保存图片到图片列表进行显示
                    this.imageList.push(fileData);
427
                } else {
428
                    Message.error(_this.$t('components.diskImageUpload.loadImageFailure1'));
429
                }
430
            }).catch((error: any) => {
431 432
                Message.error(_this.$t('components.diskImageUpload.loadImageFailure') + ':' + error);
            });
433 434
        }

435 436 437 438 439 440 441 442 443 444 445
        /**
         * 上传之前
         * @param file
         * @memberof DiskImageUplaod
         */
        public beforeUpload(file: any) {
            // 支持上传的图片格式
            let _this: any = this;
            if (!file.name.match(/^.+\.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|bmp|BMP)$/)) {
                Message.error(_this.$t('components.diskImageUpload.uploadImageFailure1'));
                return false;
446
            }
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        }

        /**
         * 自定义图片上传
         * @param param
         * @memberof DiskImageUplaod
         */
        public customImageUpload(param: any) {
            let _this: any = this;
            // 上传的文件
            let file = param.file;
            // formData传参
            let formData = new FormData();
            formData.append('file', file);
            // 拼接url
            const uploadUrl = this.getAction();
            // 发送post请求
464
            Axios.post(uploadUrl, formData, {timeout: 2000}).then((response: any) => {
465 466 467 468 469 470 471 472 473 474 475 476 477 478
                if (!response || response.status != 200) {
                    Message.error(_this.$t('components.diskImageUpload.uploadImageFailure') + "!");
                }
                // 返回的是一个jsonobject
                if (response.data) {
                    let returnData = response.data;
                    // 拼接缩略图下载url
                    const downloadUrl = '/net-disk/download/' + this.getFolder() + '/' + returnData.id + '/' + returnData.name;
                    // 发送get请求
                    Axios.get(downloadUrl, {
                        headers: {
                            'authcode': returnData.authcode
                        },
                        responseType: 'blob',
479 480
                    }).then((response2) => {
                        if (!response2 || response2.status != 200) {
481
                            Message.error(_this.$t('components.diskImageUpload.loadImageFailure') + "!");
482 483
                            return;
                        }
484
                        // 请求成功,后台返回的是一个文件流
485
                        if (response2.data) {
486
                            // 用blob对象获取文件流
487
                            let blob = new Blob([response2.data], {type: response2.headers['content-type']});
488
                            // 通过文件流创建下载链接
489
                            let href = URL.createObjectURL(blob);
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                            // 将下载链接保存到本次上传成功后返回的jsonobject中
                            returnData.url = href;
                            // 保存jsonobject中的图片fileid
                            if (returnData.fileid) {
                                this.imageFileids.push(returnData.fileid);
                            } else if (returnData.id) {
                                this.imageFileids.push(returnData.id);
                            } else {
                                Message.error(_this.$t('components.diskImageUpload.ImageIdNone'));
                                return;
                            }
                            // 保存jsonobject到图片列表进行显示
                            this.imageList.push(returnData);
                            // 新建表单上传时,后续需要批量更新操作
                            if (this.isCreate == true) {
                                this.isUpdateBatch = true;
                            }
                            // persistence=true时,需要持久化表单属性
                            if (this.persistence == true && this.imageList.length > 0) {
                                const value = JSON.stringify(this.imageList);
                                this.$emit('formitemvaluechange', {name: this.formItemName, value: value});
                            }
                        } else {
                            Message.error(_this.$t('components.diskImageUpload.loadImageFailure1'));
514
                        }
515 516
                    }).catch((error2: any) => {
                        Message.error(_this.$t('components.diskImageUpload.loadImageFailure') + ':' + error2);
517 518
                    });
                }
519 520
            }).catch((error: any) => {
                Message.error(_this.$t('components.diskImageUpload.uploadImageFailure') + ':' + error);
521
            });
522 523 524
        }


525 526 527 528 529 530 531 532 533 534
        /**
         * 预览
         * @param file
         * @memberof DiskImageUplaod
         */
        public onPreview(file: any) {
            let _this: any = this;
            if (file.url) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
535
            } else {
536
                Message.error(_this.$t('components.diskImageUpload.notImageUrl'));
537
            }
538
        }
539

540 541 542 543 544 545 546 547 548 549
        /**
         * Ocr识别
         * @param file
         * @memberof DiskImageUplaod
         */
        public onOcr(file: any) {
            // 拼接url
            const id = typeof file.id == "string" ? file.id : JSON.stringify(file.id);
            const name = typeof file.name == "string" ? file.name : JSON.stringify(file.name);
            const ocrUrl = '/net-disk/ocrview/' + this.getFolder() + '/' + id + '/' + name + '?authcode=' + file.authcode;
550 551 552 553 554 555 556 557 558 559 560 561 562
            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);
            });
563
        }
564

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
        /**
         * 下载
         * @param file
         * @memberof DiskImageUplaod
         */
        public onDownload(file: any) {
            // 拼接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 = '/net-disk/download/' + this.getFolder() + '/' + id + '/' + name;
            // 发送get请求
            Axios.get(downloadUrl, {
                headers: {
                    'authcode': file.authcode
                },
                responseType: 'blob',
582
            }).then((response: any) => {
583 584 585
                if (!response || response.status != 200) {
                    Message.error(_this.$t('components.diskImageUpload.loadImageFailure2') + '!');
                    return;
586
                }
587 588 589 590 591 592
                // 请求成功,后台返回的是一个文件流
                if (response.data) {
                    // 获取文件名
                    const disposition = response.headers['content-disposition'];
                    const filename = disposition.split('filename=')[1];
                    // 用blob对象获取文件流
593
                    let blob = new Blob([response.data], {type: response.headers['content-type']});
594
                    // 通过文件流创建下载链接
595
                    let href = URL.createObjectURL(blob);
596
                    // 创建一个a元素并设置相关属性
597
                    let a = document.createElement('a');
598
                    a.href = href;
599 600
                    if (name) {
                        a.download = name;
601
                    } else {
602 603
                        a.download = filename;
                    }
604 605 606 607 608 609 610 611 612 613 614
                    // 添加a元素到当前网页
                    document.body.appendChild(a);
                    // 触发a元素的点击事件,实现下载
                    a.click();
                    // 下载完成,从当前网页移除a元素
                    document.body.removeChild(a);
                    // 释放blob对象
                    URL.revokeObjectURL(href);
                } else {
                    Message.error(_this.$t('components.diskImageUpload.loadImageFailure3'));
                }
615
            }).catch((error: any) => {
616
                Message.error(_this.$t('components.diskImageUpload.loadImageFailure2') + ':' + error);
617 618 619 620
            });
        }


621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        /**
         * 删除
         * @param file
         * @memberof DiskImageUplaod
         */
        public onRemove(file: any) {
            let _this: any = this;
            if (file) {
                MessageBox.confirm(_this.$t('components.diskImageUpload.deleteFile'), _this.$t('components.diskImageUpload.deleteFilePrompt'), {
                    confirmButtonText: _this.$t('components.diskImageUpload.true'),
                    cancelButtonText: _this.$t('components.diskImageUpload.false'),
                    type: 'warning'
                }).then(() => {
                    if (this.imageFileids.indexOf(file.id) != -1) {
                        // 要删除的图片在图片列表中的下标
                        const index = this.imageFileids.indexOf(file.id);
                        // 拼接url
                        const deleteUrl = '/net-disk/files/' + file.id;
                        // 发送delete请求
640
                        Axios.delete(deleteUrl).then((response: any) => {
641 642 643 644 645 646 647 648 649 650 651 652
                            if (!response || response.status != 200) {
                                Message.error(_this.$t('components.diskImageUpload.deleteImageFailure') + '!');
                            }
                            // 从fileid数组中删除
                            this.imageFileids.splice(index, 1);
                            // 从图片列表中删除
                            this.imageList.splice(index, 1);
                            // persistence=true,时需要持久化表单属性
                            if (this.persistence == true) {
                                const value = JSON.stringify(this.imageList);
                                this.$emit('formitemvaluechange', {name: this.formItemName, value: value});
                            }
653
                        }).catch((error: any) => {
654 655 656 657 658 659
                            // 提示删除失败
                            Message.error(_this.$t('components.diskImageUpload.deleteImageFailure') + ':' + error);
                        });
                    }
                });
            }
660
        }
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675


        /**
         * 批量更新文件表的ownerid
         * @param files
         * @memberof DiskImageUplaod
         */
        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;
676
            }
677 678 679 680 681 682
            // 发送post请求
            Axios.post(updateUrl, requestBody, {
                headers: {
                    "Content-Type": "application/json;charset=UTF-8"
                },
                timeout: 2000
683
            }).then((response: any) => {
684 685 686 687
                if (!response || response.status != 200) {
                    Message.error(_this.$t('components.diskImageUpload.updateFailure') + '!');
                    return;
                }
688
            }).catch((error: any) => {
689 690 691
                Message.error(_this.$t('components.diskImageUpload.updateFailure') + ':' + error);
            });
        }
692 693


694
    }
695 696
</script>

697 698 699 700 701 702 703 704 705 706 707 708
<style lang="less">
    .dialogDiv {
        // el-dialog头部
        .el-dialog__header {
            height: 40px;
        }

        // el-dialog面板
        .el-dialog__wrapper {
            height: 90vh;
            overflow: visible;
        }
709

710 711 712 713 714 715 716 717 718 719
        // el-dialog
        .el-dialog {
            height: 100%;
        }

        // el-dailog内容
        .el-dialog__body {
            height: inherit;
        }

720
        // iframe
721 722 723 724
        #fileIframe {
            height: calc(100% - 40px);
        }
    }
725
</style>