jQuery进度条不适用于firefox

时间:2016-07-11 06:07:57

标签: javascript php jquery html firefox

我创建了一个用于上传单个文件的页面,我想要包含一个进度条来跟踪进度。它在chrome上完美运行(在IE和Edge上并不是那么完美,但我仍然可以给予并采取一些措施)。但是,进度条和相关的document.getElementById()无法正常工作。 Firefox跳转到显示

  

上传失败

而不是显示我的进度条动画和相关的上传数据,例如上传的字节数。奇怪的是,我的文件最终会上传,我被重定向到成功页面。甚至更奇怪的是,当我尝试使用firefox调试工具逐行遍历我的代码时,进度条和上传数据都会正确显示。

PS。这些只在localhost上测试过。

uploadfile.php
HTML部分

<form action="getfile.php" id="upload_form" method="post" enctype="multipart/form-data"><br>
    Type (or select) Filename: <input type="file" id="file1" name="uploadfile"><br>
    <input type="submit" value="Upload File" onclick="uploadFile()">
    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
    <h3 id="status"></h3>
    <p id="loaded_n_total"></p>
</form>

脚本部分

function uploadFile() {
    var file = document.getElementById("file1").files[0];
    // alert(file.name+" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append("file1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "getfile.php");
    ajax.send(formdata);
}
function progressHandler(event) {
    document.getElementById("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
    var percent = (event.loaded / event.total) * 100;
    document.getElementById("progressBar").value = Math.round(percent);
    document.getElementById("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}
function completeHandler(event) {
    document.getElementById("status").innerHTML = event.target.responseText;
    document.getElementById("progressBar").value = 0;
}
function errorHandler() {
    document.getElementById("status").innerHTML = "Upload Failed";
}
function abortHandler() {
    document.getElementById("status").innerHTML = "Upload Aborted";
}

1 个答案:

答案 0 :(得分:0)

使用jQuery避免使用被删除的方法。

 var myXhr = jQuery.ajaxSettings.xhr();
 if (myXhr.upload) {
     myXhr.upload.addEventListener('progress', custom_progress, false);
 }

然后处理进度

function custom_progress(e) {
    if (e.lengthComputable) {
        var x = (e.loaded / e.total) * 100;
        jQuery("#progress").html(x + "%");
    }
}

完整的ajax方法

jQuery.ajax({
    url: "/uploadfile.php",
    type: "POST",
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,
    xhr: function() {
        var myXhr = jQuery.ajaxSettings.xhr();
        if (myXhr.upload) {
            myXhr.upload.addEventListener('progress', custom_progress, false);
        }
        return myXhr;
    },
    success: function(response) {
        console.log(response);
    }
});