简单的jQuery进度条百分比

时间:2012-08-26 16:49:56

标签: php jquery progress-bar

我一直在努力寻找一个简单的教程,展示如何在我的文件上传中添加进度百分比的基础知识,我已经构建了我的文件上传部分,所以我不想要同时附带的插件,我我希望能够自己编写进度条代码,但我需要一些帮助来解决这个问题。我想了解它是如何工作的,我不仅仅想要一些能为我完成这一切的插件。

非常感谢任何帮助,谢谢!

我只对如何获取文件上传的百分比感兴趣,而不是真正在进度条本身上。我希望能够有一个准确的百分比。

2 个答案:

答案 0 :(得分:15)

看这里:

http://jquery.malsup.com/form/progress.html

试试这个: -

这是我的HTML代码

<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }

.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
    <h1>File Upload Progress Demo #1</h1>
    <code>&lt;input type="file" name="myfile"></code>
        <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadedfile"><br>
        <input type="submit" value="Upload File to Server">
    </form>

    <div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
    </div>

    <div id="status"></div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    complete: function(xhr) {
     bar.width("100%");
    percent.html("100%");
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

</body>
</html>

我的PHP代码

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

答案 1 :(得分:3)

请看一下,我想你会发现这个有用。它是jQuery,它有进度百分比,就像你想要的上传脚本一样!

Live Demo jsFiddle

如果你想学习更复杂的例子,我会推荐可靠的脚本,例如Uber Uploader - 它是jQuery和PHP。