自定义XMLHttpRequest上传文件

2026-05-02 12:25:38 245
分类:Web前端

做了个自定义XMLHttpRequest上传文件和webuploader插件,类似百度的webuploader,还没来得及整理。

//上传文件
function AjaxUpload(options) {
    this.url = options.url;
    this.formData = options.formData;
    this.progress = options.progress;
    this.load = options.load;
    this.error = options.error;
    this.abort = options.abort;

    this.xhr = new XMLHttpRequest();
    this.upload();
}

AjaxUpload.prototype = {
    constructor:AjaxUpload,
    upload: function () {
        var self = this;

        //进度条
        this.xhr.upload.addEventListener("progress", function (e) {
            if (self.progress) return self.progress(e);
        });
        //完成
        this.xhr.addEventListener("load", function (e) {
            console.log(self.xhr.responseText)
            if (self.load) return self.load(self.xhr);
        });
        //错误
        this.xhr.addEventListener("error", function (e) {
            if (self.error) return self.error(e);
        });
        //请求中止
        this.xhr.addEventListener("abort", function (e) {
            if (self.abort) return self.abort(e);
        });

        this.xhr.open("POST", this.url, true);
        this.xhr.send(this.formData);
    },
    abort: function () {
        this.xhr.abort();
    }
}