0

您好,我目前正在处理一个上传进度条。

这是显示上传进度条的代码:

<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury @ DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
    return document.getElementById(el);
}
function uploadFile(){
    var file = _("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", "mylistener.php");
    ajax.send(formdata);
}
function progressHandler(event){
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    _("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1"><br>
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <div id="status"></div>
  <div id="loaded_n_total"></div>
    <input type="button" value="Upload File" onclick="uploadFile()">
</form>
</body>
</html>

当我将此行更改为如下所示时: <form id="upload_form" enctype="multipart/form-data" action="mylistener.php" method="post"><input type="submit" value="Upload File" onclick="uploadFile()"> 注意我已将输入类型从更改buttonsubmit.

通过这种方式,它给了我错误“上传中止”,而不是打印上传进度条。

当我这样做时,它正在提交表单,但它没有显示上传进度条。所以我的问题是如何在我的 HTML 表单中使用输入类型 submit 和 action="mylistener.php" 并使上传进度条正常工作。这个 Javascript 中的问题在哪里,所以它没有按我想要的方式工作?

4

1 回答 1

1

当您将: input type="button" 更改为 input type="submit" 时,页面实际上会重新加载。因此它显示上传中止。如果您想将输入类型更改为“提交”,请将这行代码添加到您的 uploadFile 函数中:

    function uploadFile(){
        event.preventDefault();
        event.stopPropagation();
        //here is your rest of the code
    }

现在你的代码可以工作了..

于 2014-03-16T08:39:39.967 回答