如何取消文件上传并显示%的进度?

时间:2016-07-18 07:21:16

标签: javascript file-upload

我想取消上传并显示%的进度。我能怎么做?如果您有任何建议,请告诉我。这是我的代码:

var uploaderTable = $("#fileUploadTable");
                if (uploaderTable[0]) {
                    _uploader = new AjaxUpload(uploaderTable , {
                        action: "fileupload.ashx",
                        name: "doc",
                        onSubmit: function (file, extension) {
                            /// code
                        },
                        onComplete: function (file, response) {
                            /// code
                        }

1 个答案:

答案 0 :(得分:0)

使用XMLHttpRequest对象。要获取上传进度,请使用“progress”事件,并取消事件“abort”方法。

// get upload file element
var uploadFile = document.getElementById("uploadfile");

// Create a FormData instance
var formData = new FormData();
// Add the file 
formData.append("upload", uploadFile.files[0]);

var xhr = new XMLHttpRequest();

// to calc progress
xhr.upload.addEventListener("progress", function(e) {
    var progressPercent = parseInt(100 - (e.loaded / e.total * 100));
    // do whatever you want to do with percent
}, false);

// know when file is sent (or failed)
xhr.onreadystatechange = function(e) {
    if (xhr.readyState == 4) {
        progress.className = (xhr.status == 200 ? "success" : "failure");
    }
};

// start upload
xhr.open("POST", uploadUrl, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(formData);


// to cancel sending: xhr.abort();