VUE文件分片上传cos对象存储

6 篇文章 0 订阅

关于vue使用文件分片上传记录次文档
index.html引入

<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/spark.js"></script>
<script type="text/javascript" src="./js/dropzone.min.js"></script>

在需要分片上传的地方使用

//此处样式可更改 添加图片或者按钮 移动端(点击获取文件)PC端(拖拽获取文件)均可用
<div id="myDropzone">
  <div class="am-text-success dz-message">
     将文件拖拽到此处<br>或点此打开文件管理器选择文件
  </div>
</div>

script方法如下

export default {
        name: "dropzone",
        data() {
            return {
                Config: {}
            }
        },
        created() {
            let _that = this
            $.ajax({
                url: "配置初始化信息接口",
                data: {version: '1.2.0.20210401_beta'},
                success: function (res) {
                    _that.Config = res.data.uploaddata
                },
                error: function (err) {

                }
            })
        },
        mounted() {
            this.dropzone();
        },
        methods: {
            dropzone() {
                let _that = this
                var myDropzone = $('#myDropzone').dropzone({
                    url: function (files) {
                        console.log(files)
                        if (files[0].upload.chunked) {
                            var chunk = null;
                            files[0].upload.chunks.forEach(function (item) {
                                if (item.status === 'uploading') {
                                    chunk = item;
                                }
                            });
                            var index = chunk.dataBlock.chunkIndex;
                            // debugger;
                            this.options.headers = {"Authorization": files[0]['partsAuthorization'][index], "x-date": files[0]['date']}
                            if (!chunk) {
                                return _that.Config.uploadurl + "/" + files[0].key + "?uploadId=" + files[0].uploadId;
                            } else {
                                return _that.Config.uploadurl + "/" + files[0].key + "?partNumber=" + (index + 1) + "&uploadId=" + files[0].uploadId;
                            }
                        }
                        return _that.Config.uploadurl;
                    },
                    method: function (files) {
                        var _method = 'POST';
                        if (files[0].upload.chunked) {
                            var chunk = null;
                            files[0].upload.chunks.forEach(function (item) {
                                if (item.status === 'uploading') {
                                    chunk = item;
                                }
                            });
                            if (chunk) {
                                _method = "PUT";
                            }
                        }
                        return _method;
                    },
                    params: function (files, xhr, chunk) {
                        var params = _that.Config.multipart;
                        if (chunk) {
                            return $.extend({}, params, {
                                filesize: chunk.file.size,
                                filename: chunk.file.name,
                                chunkid: chunk.file.upload.uuid,
                                chunkindex: chunk.index,
                                chunkcount: chunk.file.upload.totalChunkCount,
                                chunkfilesize: chunk.dataBlock.data.size,
                                chunksize: this.options.chunkSize,
                                width: chunk.file.width || 0,
                                height: chunk.file.height || 0,
                                type: chunk.file.type,
                                uploadId: chunk.file.uploadId,
                                key: chunk.file.key,
                            });
                        } else {
                            params = $.extend({}, params, files[0].params);
                        }
                        return params;
                    },
                    autoQueue: false,
                    chunking: true,
                    chunkSize: 2097152, // 2M
                    maxFilesize: '10M',
                    acceptedFiles: _that.Config.mimetype,
                    maxFiles: 1,
                    timeout: 600000,
                    parallelUploads: 1,
                    previewsContainer: false,
                    dictDefaultMessage: "Drop files here to upload",
                    dictFallbackMessage: "Your browser does not support drag'n'drop file uploads",
                    dictFallbackText: "Please use the fallback form below to upload your files like in the olden days",
                    dictFileTooBig: "File is too big 10M, Max filesize: 10M",
                    dictInvalidFileType: "You can't upload files of this type",
                    dictResponseError: "Server responded with 0 code.",
                    dictCancelUpload: "Cancel upload",
                    dictUploadCanceled: "Upload canceled",
                    dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
                    dictRemoveFile: "Remove file",
                    dictMaxFilesExceeded: "You can only upload a maximum of 1 files",
                    init: function () {
                    },
                    addedfiles: function (files) {
                        var that = this;
                        var file = files[0]
                        setTimeout(function () {
                            if (file.status === 'error') {
                                return;
                            }
                            _that.getFileMd5(file, function (md5) {
                                var chunk = that.options.chunking && file.size > that.options.chunkSize ? 1 : 0;
                                $.ajax({
                                    url: "获取cos上传参数信息",
                                    type: 'POST',
                                    data: {
                                        md5: md5,
                                        name: file.name,
                                        type: file.type,
                                        size: file.size,
                                        chunk: chunk,
                                        chunksize: 2097152,
                                        costoken: _that.Config.multipart.costoken
                                    },
                                    success: function (ret) {
                                        var data = ret.data;
                                        file.md5 = md5;
                                        file.id = data.id;
                                        file.key = data.key;
                                        file.date = data.date;
                                        file.uploadId = data.uploadId;
                                        file.policy = data.policy;
                                        file.signature = data.signature;
                                        file.partsAuthorization = data.partsAuthorization;
                                        file.params = data;
                                        console.log(file.status)
                                        if (file.status != 'error') {
                                            //开始上传
                                            that.enqueueFile(file);
                                        } else {
                                            that.removeFile(file);
                                        }
                                        return false;
                                    },
                                    error: function (err) {
                                        console.log(JSON.stringify(err))
                                    }
                                })
                            });
                        }, 0);
                    },
                    chunkSuccess: function (chunk, file, response) {
                        console.log('chunkSuccess');
                        var etag = chunk.xhr.getResponseHeader("ETag").replace(/(^")|("$)/g, '');
                        this.etags = this.etags ? this.etags : [];
                        this.etags[chunk.index] = etag;
                    },
                    chunksUploaded: function (file, done) {
                        var that = this;
                        $.ajax({
                            url: "cos分片合并",
                            type: "POST",
                            data: {
                                action: 'merge',
                                filesize: file.size,
                                filename: file.name,
                                chunkid: file.upload.uuid,
                                chunkcount: file.upload.totalChunkCount,
                                md5: file.md5,
                                key: file.key,
                                uploadId: file.uploadId,
                                etags: this.etags,
                                costoken: _that.Config.multipart.costoken,
                            },
                            success: function (ret) {
                                done(JSON.stringify(ret));
                                return false;
                            },
                            error: function (err) {
                                file.accepted = false;
                                that._errorProcessing([file], err.msg);
                                return false;
                            }
                        });
                    },
                    success: function (file, response) {
                        var ret = {code: 0, msg: response};
                        try {
                            if (response) {
                                ret = typeof response === 'string' ? JSON.parse(response) : response;
                            }
                            if (file.xhr.status === 200 || file.xhr.status === 204) {
                                var url = '/' + file.key;
                                ret = {code: 1, data: {url: url}};
                                $.ajax({
                                    url: "cos上传回调",
                                    type: "POST",
                                    data: {
                                        name: file.name,
                                        url: url,
                                        md5: file.md5,
                                        size: file.size,
                                        width: file.width || 0,
                                        height: file.height || 0,
                                        type: file.type,
                                        costoken: _that.Config.multipart.costoken
                                    },
                                    success: function (ret) {
                                        return false;
                                    },
                                    error: function (err) {
                                        return false;
                                    }
                                });
                            }
                        } catch (e) {
                            console.error(e);
                        }
                    },
                    error: function (file, response, xhr) {
                        console.log(response)
                    },
                    uploadprogress: function (file, progress, bytesSent) {
                        console.log('uploadprogress')
                        console.log(progress)
                    },
                    totaluploadprogress: function (progress, bytesSent) {
                        console.log('totaluploadprogress')
                        console.log(progress)
                    },
                    queuecomplete: function () {
                        console.log('queuecomplete')
                        this.removeAllFiles(true);
                    },
                    //上传成功的回调
                    onUploadSuccess: function (up, ret, file) {
                        console.log('onUploadSuccess')
                    },
                    //上传错误的回调
                    onUploadError: function (up, ret, file) {
                        console.log('onUploadError')
                    },
                    //服务器响应数据后
                    onUploadResponse: function (response, up, file) {
                        console.log('onUploadResponse')
                    },
                    //上传全部结束后
                    onUploadComplete: function (up, files) {
                        console.log('onUploadComplete')
                    },
                    sending: function (file, xhr, formData) {
                        var that = this;
                        if (file.upload.chunked) {
                            var _send = xhr.send;
                            xhr.send = function () {
                                var chunk = null;
                                file.upload.chunks.forEach(function (item) {
                                    if (item.status == 'uploading') {
                                        chunk = item;
                                    }
                                });
                                if (chunk) {
                                    _send.call(xhr, chunk.dataBlock.data);
                                }
                            };
                        } else {

                        }
                    }
                });
            },
            getFileMd5(file, cb) {
                var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                    chunkSize = 2097152, // 2M
                    chunks = Math.ceil(file.size / chunkSize),
                    currentChunk = 0,
                    spark = new SparkMD5.ArrayBuffer(),
                    fileReader = new FileReader();

                fileReader.onload = function (e) {
                    spark.append(e.target.result);
                    currentChunk++;
                    if (currentChunk < chunks) {
                        loadNext();
                    } else {
                        cb && cb(spark.end());
                    }
                };
                fileReader.onerror = function () {
                    console.warn('文件读取错误');
                };

                function loadNext() {
                    var start = currentChunk * chunkSize,
                        end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                    fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                }

                loadNext();
            },

        },
        watch: {},
        filters: {}
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值