lijh
2022-01-12 bf6fbec0b5593eb28dc195a58a4208d29b79dfee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<template>
    <div id="global-uploader">
        <!-- 上传 -->
        <uploader ref="uploaderId" :options="options" :autoStart="false" @file-added="onFileAdded"
            @file-success="onFileSuccess" @file-progress="onFileProgress" @file-error="onFileError"
            @file-complete="onFileComplete" class="uploader-app">
            <uploader-unsupport></uploader-unsupport>
 
            <uploader-btn id="global-uploader-btn" :directory="false" :attrs="attrs" ref="uploadBtn">选择文件</uploader-btn>
 
            <uploader-list v-show="panelShow">
                <div class="file-panel" slot-scope="props" :class="{'collapse': collapse}">
                    <div class="file-title">
                        <h2>文件列表</h2>
                        <div class="operate">
                            <el-button @click="fileListShow" type="text" :title="collapse ? '展开':'折叠' ">
                                <i class="iconfont" :class="collapse ? 'inuc-fullscreen': 'inuc-minus-round'"></i>
                            </el-button>
                            <el-button @click="close" type="text" title="关闭">
                                <i class="iconfont icon-close"></i>
                            </el-button>
                        </div>
                    </div>
 
                    <ul class="file-list">
                        <li v-for="file in props.fileList" :key="file.id">
                            <uploader-file :class="'file_' + file.id" ref="files" :file="file" :list="true">
                            </uploader-file>
                        </li>
                        <div class="no-file" v-if="!props.fileList.length"><i class="iconfont icon-empty-file"></i>
                            暂无待上传文件</div>
                    </ul>
                </div>
            </uploader-list>
 
        </uploader>
 
    </div>
</template>
 
<script>
    /**
     *   全局上传插件
     *   调用方法:Bus.$emit('openUploader', {}) 打开文件选择框,参数为需要传递的额外参数
     *   监听函数:Bus.$on('fileAdded', fn); 文件选择后的回调
     *            Bus.$on('fileSuccess', fn); 文件上传成功的回调
     */
 
    import {
        ACCEPT_CONFIG
    } from '@/js/config';
    import Bus from '@/js/bus';
    import SparkMD5 from 'spark-md5';
    import $ from 'jquery';
    import Element from 'element-ui';
 
    // 这两个是我自己项目中用的,请忽略
    // import {Ticket} from '@/assets/js/utils';
    // import api from '@/api';
 
    export default {
        data() {
            return {
                options: {
                    //target: "http://192.168.21.184:8089/aa",
                    chunkSize: 6 * 1024 * 1024,
                    fileParameterName: 'upFile',
                    forceChunkSize: true,
                    maxChunkRetries: 3,
                    testChunks: true, //是否开启服务器分片校验
                    // 服务器分片校验函数,秒传及断点续传基础
                    checkChunkUploadedByResponse: function(chunk, message) {
                        let resp = JSON.parse(message);
                        if (!resp.success) {
                            console.error("校验分片异常")
                            return false;
                        }
 
                        //已经秒传
                        if (resp.result.chunkIndex != null && resp.result.chunkIndex[chunk.offset] > 0) {
                            console.log(chunk.offset + 1 + "已经秒传..")
                            return true;
                        }
                        console.log(chunk.offset + 1 + "正常上传..")
 
                        return false;
                    },
                    headers: {
                        // Authorization: Ticket.get() && "Bearer " + Ticket.get().access_token
                    },
                    query() {
                        //aa: "bbb";
                    }
                },
                attrs: {
                    accept: ACCEPT_CONFIG.getAll()
                },
                panelShow: true, //选择文件后,展示上传panel
                collapse: true,
            }
        },
        mounted() {
            Bus.$on('openUploader', query => {
                this.params = query || {};
 
                if (this.$refs.uploadBtn) {
                    $('#global-uploader-btn').click();
                }
            });
        },
        computed: {
            //Uploader实例
            uploader() {
                return this.$refs.uploaderId.uploader;
            }
        },
        methods: {
            onFileAdded(file) {
                
                this.panelShow = true;
                this.computeMD5(file);
 
                Bus.$emit('fileAdded');
            },
 
            onFileComplete(rootFile) {
                console.log(11111)
                console.log(rootFile)
            },
            onFileProgress(rootFile, file, chunk) {
                console.log(`上传中 ${file.name},chunk:${chunk.startByte / 1024 / 1024} ~ ${chunk.endByte / 1024 / 1024}`)
            },
            onFileSuccess(rootFile, file, response, chunk) {
                console.log("上传完成回调", response);
                let res;
                try {
                    if (typeof response =="string") {
                        res = JSON.parse(response);
                    } else {
                        res = response;
                    }
                    // 服务器自定义的错误(即虽返回200,但是是错误的情况),这种错误是Uploader无法拦截的
                    if (!res.success) {
                        this.$message({
                            message: res.errmsg,
                            type: 'error'
                        });
                        // 文件状态设为“失败”
                        this.statusSet(file.id, 'failed');
                        return
                    }
 
                } catch (ex) {
                    console.log(ex)
                }
 
                var $this = this;
 
 
                // 文件状态设为“合并中”
                $this.statusSet(file.id, 'merging');
 
                //请求合并
                $this.$axios.get('http://192.168.21.184:8001/commonFileUpload/doMerge?mainMD5=' + file.uniqueIdentifier +
                        "&mediaId=" + localStorage.getItem("mediaId"))
                    .then(function(response) {
 
                        if (response.data.success) {
                            // 文件合并成功
                            Bus.$emit('fileSuccess');
                            $this.statusRemove(file.id);
 
                            console.log('文件合并成功');
                            console.log('上传成功');
                            console.log("文件上传结束" + new Date().getTime())
                        } else {
                            //请求合并异常 
                            $this.statusRemove(file.id);
                            $this.statusSet(file.id, 'mergingExcetion');
                        }
 
                    })
                    .catch(function(error) {
                        console.error(error);
                        $this.$message({
                            message: "合并异常",
                            type: 'error'
                        });
                        $this.statusRemove(file.id);
                        $this.statusSet(file.id, 'mergingExcetion');
                    });
 
 
            },
 
            onFileError(rootFile, file, response, chunk) {
                this.$message({
                    message: response,
                    type: 'error'
                })
            },
 
            /**
             * 计算md5,实现断点续传及秒传
             * @param file
             */
            computeMD5(file) {
                let fileReader = new FileReader();
                let time = new Date().getTime();
                console.log("文件上传开始" + new Date().getTime())
                let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
 
                let currentChunk = 0;
                const chunkSize = 6 * 1024 * 1024; //md5计算时切片大小
                let chunks = Math.ceil(file.size / chunkSize);
 
                let spark = new SparkMD5.ArrayBuffer();
 
                // 文件状态设为"计算MD5"
                this.statusSet(file.id, 'md5');
                file.pause();
 
                loadNext();
 
                fileReader.onload = (e => {
                    spark.append(e.target.result);
 
                    if (currentChunk < chunks) {
                        currentChunk++;
                        loadNext();
 
                        // 实时展示MD5的计算进度
                        this.$nextTick(() => {
                            $(`.myStatus_${file.id}`).text('校验MD5 ' + ((currentChunk / chunks) * 100)
                                .toFixed(0) + '%')
                        })
                    } else {
                        let md5 = spark.end();
                        this.computeMD5Success(md5, file);
                        console.log(
                            `MD5计算完毕:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${file.size} 用时:${new Date().getTime() - time} ms`
                        );
                    }
                });
 
                fileReader.onerror = function() {
                    this.error(`文件${file.name}读取出错,请检查该文件`)
                    file.cancel();
                };
 
                function loadNext() {
                    let start = currentChunk * chunkSize;
                    let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
 
                    fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
                }
            },
 
            computeMD5Success(md5, file) {
                //1.初始化分片上传请求,获取分片参数
 
                //计算内网ip是否联通,选择上传接口url,如果是
 
                let $this = this;
                //this.$axios.post('http://192.168.21.184:8001/commonFileUpload/createShardPost', {
                this.$axios.post('http://192.168.21.184:8001/sfcMedia/addMedia', {
                        storeType: "0",
                        title: file.name,
                        typeId: "4",
                        dirId: "7",
                        uploadDto: {
                            internalHostList:["192.168.40.149:9000"],
                            mainMD5: md5,
                            size: file.size,
                            fileName: file.name,
                            ext: file.name.substring(file.name.lastIndexOf(".") + 1, file.name.length), //文件名没有点号会异常
                            type: file.type
                        }
                    }, {
                        headers: {
                            'Sys-Access-Token': "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbktleU5hbWUiOiJTeXMtQWNjZXNzLVRva2VuIiwidXNlck5hbWUiOiJhZG1pbiIsImV4cCI6MTY0MTM3OTQ0NX0.FQXRgkLXlmgpLDcP2cbZZBNwCEDZJoeoHen6OZz5Wbk",
                        }
                    }).then(function(response) {
                        console.log("文件上传请求初始化");
                        console.log(response);
                        if (response.data.success) {
                            let uploadOptions = response.data.result;
 
                            localStorage.setItem("mediaId",uploadOptions.mediaId)
                            let uploadURLArray = uploadOptions.uploadUrlList;
                            
                            
                            console.log("文件上传url", uploadURLArray)
                            // 将自定义参数直接加载uploader实例的opts上
                            let opts = $this.uploader.opts;
 
                            //opts.target = "http://192.168.21.184:8001/commonFileUpload/doUpload"; //上传接口
                            opts.target = function(file, chunk, isTest, obj) {
                                //定义分片检测url
                                if (isTest) {
                                    return "http://192.168.21.184:8001/commonFileUpload/checkShardStatus"
                                }
                                let chunkUploadUrl = uploadURLArray[chunk.offset]
                                if (chunkUploadUrl == undefined || chunkUploadUrl == null || chunkUploadUrl ==
                                    "") {
                                    console.error("获取分片上传链接异常 chunkNumber:{}", (chunk.offset + 1))
                                    return "";
                                }
                                return chunkUploadUrl;
                            }
 
                            //分片请求成功后处理
                            opts.processResponse = function(response, cb, file, chunk) {
                                console.log("分片" + (chunk.offset + 1) + "上传成功", response)
 
                                //通知服务器分片上传状态
                                $this.$axios.get(
                                        'http://192.168.21.184:8001/commonFileUpload/updateProgress?mainMD5=' +
                                        file.uniqueIdentifier +
                                        "&chunk=" + (chunk.offset + 1) +
                                        "&chunkSize=" + (chunk.loaded)
                                    )
                                    .then(function(re) {
                                        console.log("分片更新上传进度成功", re)
                                        cb(null, re.data)
                                    })
                                    .catch(function(error) {
                                        console.error("分片更新上传进度异常", error);
                                        cb(null, error)
                                    });
 
                            }
 
                            opts.processParams = function(params, file, chunk, isTest) {
                                if (isTest) {
                                    return params;
                                }
                                return {};
                            }
 
                            opts.method = "octet";
                            opts.testMethod = "GET"; //调用分片上传验证请求类型
                            opts.uploadMethod = "PUT"; //调用分片上传时使用的http方法请求类型
 
                            //opts.chunkSize = uploadOptions.chunkSize; //切片大小
                            $this.params.mainMD5 = md5; //mainMD5参数
                            $this.params.chunkNumber = opts.chunkNumber; //分片索引参数
                            Object.assign(opts, {
                                query: {
                                    ...$this.params,
                                }
                            })
 
                            file.uniqueIdentifier = md5;
                            file.resume();
                            $this.statusRemove(file.id);
                        } else {
                            //中断上传
                            file.cancel();
                        }
                    })
                    .catch(function(error) {
                        console.error(error);
                        //中断上传
                        file.cancel();
                        return;
                    });
 
 
            },
 
            fileListShow() {
                let $list = $('#global-uploader .file-list');
 
                if ($list.is(':visible')) {
                    $list.slideUp();
                    this.collapse = true;
                } else {
                    $list.slideDown();
                    this.collapse = false;
                }
            },
            close() {
                this.uploader.cancel();
 
                this.panelShow = false;
            },
 
            /**
             * 新增的自定义的状态: 'md5'、'transcoding'、'failed'
             * @param id
             * @param status
             */
            statusSet(id, status) {
                let statusMap = {
                    md5: {
                        text: '校验MD5',
                        bgc: '#fff'
                    },
                    merging: {
                        text: '合并中',
                        bgc: '#e2eeff'
                    },
                    mergingExcetion: {
                        text: '合并异常',
                        bgc: '#e2eeff'
                    },
                    transcoding: {
                        text: '转码中',
                        bgc: '#e2eeff'
                    },
                    failed: {
                        text: '上传失败',
                        bgc: '#e2eeff'
                    }
                }
 
                this.$nextTick(() => {
                    $(`<p class="myStatus_${id}"></p>`).appendTo(`.file_${id} .uploader-file-status`).css({
                        'position': 'absolute',
                        'top': '0',
                        'left': '0',
                        'right': '0',
                        'bottom': '0',
                        'zIndex': '1',
                        'backgroundColor': statusMap[status].bgc
                    }).text(statusMap[status].text);
                })
            },
            statusRemove(id) {
                this.$nextTick(() => {
                    $(`.myStatus_${id}`).remove();
                })
            },
 
            error(msg) {
                this.$notify({
                    title: '错误',
                    message: msg,
                    type: 'error',
                    duration: 2000
                })
            }
        },
        watch: {},
        destroyed() {
            Bus.$off('openUploader');
        },
        components: {}
    }
</script>
 
<style>
    #global-uploader {
        position: fixed;
        z-index: 20;
        right: 15px;
        bottom: 15px;
    }
 
    #global-uploader .uploader-app {
        width: 1820px;
    }
 
    #global-uploader .file-panel {
        background-color: #fff;
        border: 1px solid #e2e2e2;
        border-radius: 7px 7px 0 0;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    }
 
    #global-uploader .file-panel .file-title {
        display: flex;
        height: 40px;
        line-height: 40px;
        padding: 0 15px;
        border-bottom: 1px solid #ddd;
    }
 
    #global-uploader .file-panel .file-title .operate {
        flex: 1;
        text-align: right;
    }
 
    #global-uploader .file-panel .file-list {
        position: relative;
        height: 240px;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: #fff;
    }
 
    #global-uploader .file-panel .file-list>li {
        background-color: #fff;
    }
 
    #global-uploader .file-panel.collapse .file-title {
        background-color: #E7ECF2;
    }
 
    #global-uploader .no-file {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 16px;
    }
 
    #global-uploader .uploader-file-icon:before {
        content: "" !important;
    }
 
    #global-uploader .uploader-file-actions>span {
        margin-right: 6px;
    }
 
    #global-uploader .uploader-file-icon[icon=image] {
        background: url(../images/image-icon.png);
    }
 
    #global-uploader .uploader-file-icon[icon=video] {
        background: url(../images/video-icon.png);
    }
 
    #global-uploader .uploader-file-icon[icon=document] {
        background: url(../images/text-icon.png);
    }
 
    /* 隐藏上传按钮 */
    #global-uploader-btn {
        position: absolute;
        clip: rect(0, 0, 0, 0);
    }
</style>