bootstrap.js 9.1 KB
//修改上传的接口调用
require(['upload', '../addons/upyun/js/spark'], function (Upload, SparkMD5) {
    //获取文件MD5值
    var getFileMd5 = function (file, cb) {
        var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
            chunkSize = 2097152,
            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();
    };

    //初始化中完成判断
    Upload.events.onInit = function () {
        //如果上传接口不是七牛云,则不处理
        if (this.options.url !== Config.upload.uploadurl) {
            return;
        }
        var _success = this.options.success;

        $.extend(this.options, {
            //关闭自动处理队列功能
            autoQueue: false,
            chunkSuccess: function (chunk, file, response) {
                this.etags = this.etags ? this.etags : [];
            },
            chunksUploaded: function (file, done) {
                var that = this;
                Fast.api.ajax({
                    url: "/addons/upyun/index/upload",
                    data: {
                        action: 'merge',
                        filesize: file.size,
                        filename: file.name,
                        chunkid: file.upload.uuid,
                        chunkcount: file.upload.totalChunkCount,
                        width: file.width || 0,
                        height: file.height || 0,
                        type: file.type,
                        upyuntoken: Config.upload.multipart.upyuntoken,
                        url: file.params.url,
                        uuid: file.params.uuid,
                        etags: this.etags
                    },
                }, function (data, ret) {
                    done(JSON.stringify(ret));
                    return false;
                }, function (data, ret) {
                    file.accepted = false;
                    that._errorProcessing([file], ret.msg);
                    return false;
                });

            },
        });

        this.on("addedfile", function (file) {
            var that = this;
            setTimeout(function () {
                if (file.status === 'error') {
                    return;
                }
                var index = Layer.load();
                getFileMd5(file, function (md5) {
                    var chunk = that.options.chunking && file.size > that.options.chunkSize ? 1 : 0;
                    Fast.api.ajax({
                        url: "/addons/upyun/index/params",
                        data: {method: 'POST', md5: md5, name: file.name, type: file.type, size: file.size, chunk: chunk, chunkSize: that.options.chunkSize, upyuntoken: Config.upload.multipart.upyuntoken},
                    }, function (data) {
                        Layer.close(index);
                        file.md5 = md5;
                        file.url = data.url;
                        file.headers = data.headers;
                        file.params = data;
                        that.options.chunkSize = data.chunkSize;
                        if (file.status != 'error') {
                            //开始上传
                            that.enqueueFile(file);
                        } else {
                            that.removeFile(file);
                        }
                        return false;
                    }, function () {
                        Layer.close(index);
                    });
                });
            }, 0);
        });

        //先移除已有的事件
        this.off("success", _success).on("success", function (file, response) {
            var ret = {code: 0, msg: response};
            try {
                ret = typeof response === 'string' ? (response ? JSON.parse(response) : {url: file.url}) : response;
                if (file.xhr.status === 200) {
                    console.log("SUCCESS:", ret);
                    if (typeof ret.url !== 'undefined' && typeof ret.data === 'undefined') {
                        ret = {code: 1, msg: "", data: {url: ret.url}};
                    }
                    Fast.api.ajax({
                        url: "/addons/upyun/index/notify",
                        data: {name: file.name, url: ret.data.url, md5: file.md5, size: file.size, width: file.width || 0, height: file.height || 0, type: file.type, upyuntoken: Config.upload.multipart.upyuntoken}
                    }, function () {
                        return false;
                    }, function () {
                        return false;
                    });
                }
            } catch (e) {
                console.error(e);
            }
            _success.call(this, file, ret);
        });

        this.options.params = function (files, xhr, chunk) {
            var params = Config.upload.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,
                    url: chunk.file.params.url || "",
                    uuid: chunk.file.params.uuid || "",
                });
            } else {
                if (Config.upload.uploadmode === 'client') {

                }
            }
            return params;
        };

        //如果是直传模式
        if (Config.upload.uploadmode === 'client') {
            var _url = this.options.url;

            //分片上传时URL链接不同
            this.options.url = function (files) {
                if (files[0].upload.chunked) {
                    var chunk = null;
                    files[0].upload.chunks.forEach(function (item) {
                        if (item.status === 'uploading') {
                            chunk = item;
                        }
                    });
                    if (!chunk) {
                        return Config.upload.uploadurl + files[0].url + files[0].size;
                    } else {
                        this.options.headers = $.extend(this.options.headers, chunk.file.headers, {"Cache-Control": null, "User-agent": null, "X-Upyun-Part-Id": chunk.index + ""});
                        return Config.upload.uploadurl + files[0].url;
                    }
                } else {
                    this.options.headers = $.extend(this.options.headers, files[0].headers, {"Cache-Control": null, "User-agent": null});
                    return Config.upload.uploadurl + files[0].url;
                }
                return _url;
            };

            var _method = this.options.method;
            this.options.method = function (files) {
                if (files[0].upload.chunked) {
                    var chunk = null;
                    files[0].upload.chunks.forEach(function (item) {
                        if (item.status === 'uploading') {
                            chunk = item;
                        }
                    });
                    if (!chunk) {
                        return "POST";
                    } else {
                        return "PUT";
                    }
                } else {
                    return "PUT";
                }
                return _method;
            };

            //分片上传时需要变更提交的内容
            this.on("sending", function (file, xhr, formData) {
                if (true) {
                    var _send = xhr.send;
                    xhr.send = function () {
                        if (file.upload.chunked) {
                            var chunk = null;
                            file.upload.chunks.forEach(function (item) {
                                if (item.status == 'uploading') {
                                    chunk = item;
                                }
                            });
                            if (chunk) {
                                _send.call(xhr, chunk.dataBlock.data);
                            }
                        } else {
                            _send.call(xhr, file);
                        }
                    };
                }
            });
        }
    };

});