ibiz-file-upload.vue 19.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<template>
    <div id="file-upload">
        <el-row id="el-row">
            <!--拖拽上传-->
            <el-col v-if="showDrag==true" class="withDrag">
                <el-upload
                        ref="upload"
                        drag
                        multiple
                        list-type="text"
11
                        :action="getAction"
12 13 14 15
                        :headers="myHeaders"
                        :file-list="uploadFileList"
                        :show-file-list="false"
                        :limit="limit"
16
                        :http-request="customUploadFile">
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
                    <div>
                        <i class="el-icon-upload"></i>
                        <div>
                            <span>将文件拖到此处,或</span>
                            <span style="color:#409EFF;">点击上传</span>
                        </div>
                        <div slot="tip" class="el-upload__tip">{{uploadTip}}</div>
                    </div>
                </el-upload>
            </el-col>
            <!--点击上传-->
            <el-col v-else class="withoutDrag">
                <el-upload
                        ref="upload"
                        multiple
                        list-type="text"
33 34
                        :action="getAction"
                        :headers="myHeaders"
35 36 37
                        :file-list="uploadFileList"
                        :show-file-list="false"
                        :limit="limit"
38
                        :http-request="customUploadFile">
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
                    <el-button type="primary" size="small" icon="el-icon-upload">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">{{uploadTip}}</div>
                </el-upload>
            </el-col>
            <!--文件操作-->
            <el-col v-for="(item,index) in uploadFileList" :key="index" class="fileList">
                <div class="fileTitle">
                    <i class="el-icon-document"></i>
                    <span>{{item.name}}</span>
                </div>
                <div class="fileMain">
                    <el-link type="success" icon="el-icon-download" @click="onDownload(item)">下载</el-link>
                    <el-link type="warning" icon="el-icon-view" v-show="showPreview" @click="onPreview(item)">预览
                    </el-link>
                    <el-link type="primary" icon="el-icon-edit"
54
                             v-show="showEdit && (item.name.match(/^.+\.(doc|DOC|docx|DOCX|wps|WPS|xls|XLS|xlsx|XLSX|ppt|PPT|et|ET)$/))"
55 56 57
                             @click="onEdit(item)">编辑
                    </el-link>
                    <el-link icon="el-icon-camera"
58
                             v-show="showOcrview && (item.name.match(/^.+\.(gif|GIF|jpg|JPG|jpeg|JPEG|png|PNG|bmp|BMP|pdf|PDF)$/))"
59 60 61 62 63 64 65 66 67 68 69 70
                             @click="onOcr(item)">OCR
                    </el-link>
                    <el-link type="danger" icon="el-icon-delete" @click="onRemove(item,index)">删除</el-link>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import {Button, Row, Col, Link, Icon, Upload, Message, MessageBox} from 'element-ui';
    import Axios from 'axios';
71 72 73 74
    import {Subject, Unsubscribable} from 'rxjs';

    // 当前登录人token
    var token = "Bearer " + localStorage.getItem('token');
75 76 77 78 79 80 81 82 83 84 85 86

    export default {
        name: "ibiz-file-upload",
        components: {
            'el-button': Button,
            'el-row': Row,
            'el-col': Col,
            'el-link': Link,
            'el-icon': Icon,
            'el-upload': Upload,
        },
        props: {
87
            // 当前表单对象
88 89 90 91
            data: {
                type: Object,
            },
            // 当前属性名
92
            formItemName: {
93 94 95 96 97 98
                type: String,
            },
            // 当前属性值
            value: {
                type: String,
            },
99 100 101 102
            // 订阅表单状态
            formState: {
                type: Subject
            },
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
            // 默认为当前实体名称,有指定则按表单参数
            folder: {
                type: String,
            },
            // 默认为当前实体主键id,有指定则按表单参数
            ownerid: {
                type: String,
            },
            // 默认为当前属性名,有指定则按表单参数
            ownertype: {
                type: String,
            },
            // 持久化
            persistence: {
                type: Boolean,
                default: false
            },
            // 是否显示拖拽区域
            showDrag: {
                type: Boolean,
                default: false
            },
            // 是否显示预览按钮
            showPreview: {
                type: Boolean,
                default: false
            },
            // 是否显示在线编辑按钮
            showEdit: {
                type: Boolean,
                default: false
            },
            // 是否显示OCR按钮
            showOcrview: {
                type: Boolean,
                default: false
            },
            // 单文件大小
            size: {
                type: Number,
                default: 1
            },
            // 文件上传个数
            limit: {
                type: Number,
                default: 5
            },
        },
        data() {
            return {
153 154
                // 表单是否处于编辑状态(有真实主键,srfuf='1';srfuf='0'时处于新建未保存)
                srfuf: '0',
155 156 157 158 159 160
                // 上传提示语
                uploadTip: `单个文件大小不超过${this.size}M,文件不超过${this.limit}个`,
                // 文件列表
                uploadFileList: [],
                // headers
                myHeaders: {Authorization: token},
161 162 163 164 165 166
                // 表单状态事件
                formStateEvent: Unsubscribable | undefined,
                // 批量更新标识,false为不更新,true才可以更新
                isUpdateBatch: true,
                // 新建状态标识,true为新建,false为编辑
                isCreate: true,
167 168 169
            }
        },
        computed: {
170 171 172 173
            /**
             * return action
             */
            getAction() {
174
                const uploadUrl = '/net-disk/upload/' + this.getFolder + '?ownertype=' + this.getOwnertype + '&ownerid=' + this.getOwnerid;
175 176 177 178 179 180
                return uploadUrl;
            },
            /**
             *  return folder
             */
            getFolder() {
181
                const folder = typeof this.folder == "string" ? this.folder : JSON.stringify(this.folder);
182 183 184 185 186 187
                return folder;
            },
            /**
             *  return ownertype
             */
            getOwnertype() {
188
                const ownertype = typeof this.ownertype == "string" ? this.ownertype : JSON.stringify(this.ownertype);
189 190 191 192 193 194
                return ownertype;
            },
            /**
             *  return ownerid
             */
            getOwnerid() {
195
                const ownerid = typeof this.ownerid == "string" ? this.ownerid : JSON.stringify(this.ownerid);
196
                return ownerid;
197 198
            }
        },
199 200 201 202 203 204 205 206 207 208
        watch: {},
        created() {
            this.formStateEvent = this.formState.subscribe(($event) => {
                // 表单加载完成
                if (Object.is($event.type, 'load')) {
                    const data = JSON.parse(JSON.stringify($event.data));
                    // 编辑表单,保存时不进行批量更新
                    if (data.srfuf == '1') {
                        this.isCreate = false;
                        this.isUpdateBatch = false;
209
                    }
210 211 212 213 214 215 216 217
                    // 当persistence = true时
                    if (this.persistence == true) {
                        // 直接从表单的data数据里获取当前属性的值
                        if (data[this.formItemName] && this.uploadFileList.length == 0) {
                            const files = JSON.parse(data[this.formItemName]);
                            for (let i = 0; i < files.length; i++) {
                                this.uploadFileList.push(files[i]);
                            }
218
                        }
219 220 221
                    } else {
                        // 发送get请求获取文件列表
                        this.getFiles();
222
                    }
223 224 225 226 227 228 229 230 231
                }
                // 表单保存完成
                if (Object.is($event.type, 'save')) {
                    // 批量更新文件表中的ownerid
                    if (this.isUpdateBatch == true && this.uploadFileList.length > 0) {
                        this.updateFileBatch(this.uploadFileList, 'update');
                    }
                }
            });
232 233
        },
        mounted() {
234

235 236 237 238 239 240
        },
        methods: {
            /**
             * 获取文件列表
             */
            getFiles() {
241
                // 拼接url
242
                const getUrl = '/net-disk/files/' + this.getFolder;
243
                // 发送get请求
244 245
                Axios.get(getUrl, {
                    params: {
246 247
                        ownertype: this.getOwnertype,
                        ownerid: this.getOwnerid,
248 249 250
                    },
                }).then(response => {
                    if (!response || response.status != 200) {
251
                        Message.error("获取文件列表失败!");
252 253
                        return;
                    }
254
                    // 返回的是一个jsonArray
255 256
                    if (response.data) {
                        const files = JSON.parse(JSON.stringify(response.data));
257 258 259
                        if (this.uploadFileList.length == 0) {
                            this.uploadFileList.push.apply(this.uploadFileList, files);
                        }
260 261
                    }
                }).catch(error => {
262
                    Message.error("获取文件列表失败:" + error);
263 264 265
                });
            },
            /**
266
             * 自定义上传文件
267
             */
268
            customUploadFile(param) {
269 270
                // 上传的文件
                let file = param.file;
271
                // 文件大小
272 273 274 275 276
                const isSize = file.size / 1024 / 1024 < this.size;
                if (!isSize) {
                    Message.error(`上传失败,单个文件不得超过${this.size}M!`);
                    return;
                }
277
                // formData传参
278 279
                let formData = new FormData();
                formData.append('file', file);
280 281 282 283 284 285
                // 拼接url
                const uploadUrl = this.getAction;
                // 发送post请求
                Axios.post(uploadUrl, formData, {timeout: 2000}).then(response => {
                    if (!response || response.status != 200) {
                        Message.error('上传文件失败!');
286
                    }
287 288 289 290 291 292 293 294 295 296 297 298 299
                    // 返回的是一个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});
                        }
300
                    }
301 302 303
                }).catch(err => {
                    Message.error('上传文件失败:' + err);
                });
304 305 306 307 308 309
            },
            /**
             * 下载文件
             * @param item
             */
            onDownload(item) {
310
                // 拼接url
311
                const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
312
                const name = typeof item.name == "string" ? item.name : JSON.stringify(item.filename);
313
                const downloadUrl = '/net-disk/download/' + this.getFolder + '/' + id + '/' + name;
314
                // 发送get请求
315 316
                Axios.get(downloadUrl, {
                    headers: {
317
                        'authcode': item.authcode
318
                    },
319
                    responseType: 'arraybuffer',
320 321
                }).then(response => {
                    if (!response || response.status != 200) {
322
                        Message.error("下载文件失败!");
323 324
                        return;
                    }
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
                    // 请求成功,后台返回的是一个文件流
                    if (response.data) {
                        // 获取文件名
                        const disposition = response.headers['content-disposition'];
                        const filename = disposition.split('filename=')[1];
                        // 用blob对象获取文件流
                        var blob = new Blob([response.data], {type: response.headers['content-type']});
                        // 创建下载链接
                        var href = URL.createObjectURL(blob);
                        // 创建一个a元素并设置相关属性
                        var a = document.createElement('a');
                        a.href = href;
                        a.download = filename;
                        // 添加a元素到当前网页
                        document.body.appendChild(a);
                        // 触发a元素的点击事件,实现下载
                        a.click();
                        // 从当前网页移除a元素
                        document.body.removeChild(a);
                        // 释放blob对象
                        URL.revokeObjectURL(href);
                    } else {
                        Message.error('下载文件失败,未获取到文件!');
                    }
349
                }).catch(error => {
350
                    Message.error("下载文件失败:" + error);
351 352 353 354 355 356 357
                });
            },
            /**
             * 预览文件
             * @param item
             */
            onPreview(item) {
358
                // 拼接url
359 360
                const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
                const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name);
361
                const previewUrl = '/net-disk/preview/' + this.getFolder + '/' + id + '/' + name + '?authcode=' + item.authcode;
362 363
                // 新窗口打开url
                window.open(previewUrl);
364 365 366 367 368 369
            },
            /**
             * 编辑文件
             * @param item
             */
            onEdit(item) {
370
                // 拼接url
371 372
                const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
                const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name);
373
                const editUrl = '/net-disk/edit/' + this.getFolder + '/' + id + '/' + name + '?authcode=' + item.authcode;
374 375
                // 新窗口打开url
                window.open(editUrl);
376 377 378 379 380 381
            },
            /**
             * ocr识别
             * @param item
             */
            onOcr(item) {
382
                // 拼接url
383 384
                const id = typeof item.id == "string" ? item.id : JSON.stringify(item.id);
                const name = typeof item.name == "string" ? item.name : JSON.stringify(item.name);
385
                const ocrUrl = '/net-disk/ocrview/' + this.getFolder + '/' + id + '/' + name + '?authcode=' + item.authcode;
386 387
                // 新窗口打开url
                window.open(ocrUrl);
388 389 390 391 392 393 394 395 396 397 398 399 400
            },
            /**
             * 删除文件
             * @param item
             * @param index
             */
            onRemove(item, index) {
                if (item) {
                    MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
401
                        // 拼接url
402
                        const deleteUrl = '/net-disk/files/' + item.id;
403 404 405 406 407 408
                        // 发送delete请求
                        Axios.delete(deleteUrl).then(response => {
                            if (!response || response.status != 200) {
                                Message.error("删除文件失败!");
                            }
                            // 从文件列表中删除
laizhilong's avatar
laizhilong committed
409
                            this.uploadFileList.splice(index, 1);
410 411 412 413 414 415 416 417
                            // persistence=true时需要持久化表单属性
                            if (this.persistence == true) {
                                const value = JSON.stringify(this.uploadFileList);
                                this.$emit('formitemvaluechange', {name: this.formItemName, value: value});
                            }
                        }).catch(error => {
                            // 提示删除失败
                            Message.error("删除文件失败:" + error);
418 419 420 421 422
                        });
                    });
                }
            },
            /**
423
             * 批量更新文件表的ownerid
424
             */
425 426
            updateFileBatch(files, opt) {
                // 拼接url
427
                const updateUrl = '/net-disk/files/' + this.getFolder + '?ownertype=' + this.getOwnertype + "&ownerid=" + this.getOwnerid;
428 429 430 431
                // requestBody参数
                let requestBody = [];
                if (files) {
                    requestBody = files;
432
                }
433 434 435 436 437 438 439 440 441 442 443 444 445 446
                // 发送post请求
                Axios.post(updateUrl, requestBody, {
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8"
                    },
                    timeout: 2000
                }).then(response => {
                    if (!response || response.status != 200) {
                        Message.error("批量更新文件失败!");
                        return;
                    }
                }).catch(error => {
                    Message.error("批量更新文件失败:" + error);
                });
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
            },

        }
    }
</script>

<style scoped>
    #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;
    }

    .el-upload__tip {
        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;
    }
</style>