2012-08-26 148 views
11

我一直在试图找到一个简单的教程,显示如何添加进度百分比到我的文件上传的基础知识,我已经建立了我的文件上传部分,所以我不想要一个插件两者都有,我希望能够自己编写进度条,但我需要一些帮助来解决这个问题。我想了解它是如何工作的,我不只是想要一些插件来完成这一切。简单的jQuery进度条百分比

任何帮助将不胜感激,谢谢!

我只是想知道如何获得文件上传的百分比,而不是真的在进度条本身。我希望能够有一个准确的百分比。

回答

14

看看这里:

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!"; 
} 
?> 
+0

这是我的测试代码。用百分比进度条上传文件。尝试一下。 –

+0

保险。经过3天的连续奋斗,这个答案拯救了我。非常感谢bhaijaan Abid。 – trollster

+0

@IliaRostovtsev,发布代码以及链接的全部要点是,如果链接变得不可用(暂时或永久),则该代码仍可在本网站上供用户查看和使用。不要只是发布链接作为答案,始终提供代码。 – TheCarver

3

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

Live Demo jsFiddle

如果您想了解更多复杂的例子,有可靠的剧本我会建议,
称为Uber Uploader - 这是jQuery和PHP。