显示基于百分比的进度条是棘手的工作。如果您对此主题的了解有限,则显示装载状态或旋转图标会更好。
不是最漂亮的方法,但为我和其他许多人创造了奇迹。
CSS:
#uploadFrame {
height:1px;
width:1px;
visibility:hidden;
}
HTML:
// hide this on your page somewhere. It's only 1x1 pixels, so should be simple.
<iframe src="zip_upload.php" name="uploadFrame" id="uploadFrame"></iframe>
// your upload form
<form enctype="multipart/form-data" method="post" action="zip_upload.php" target="uploadFrame">
// form content
</form>
的jQuery:
$(form).submit(function() {
$('#loading-spinner').show();
});
$("#uploadFrame").load(function() {
$('#loading-spinner').hide();
});
当提交表单时,一显示加载图标,当上传和提取过程完成时(加载iFrame),加载图标消失。这一切都发生,无需重新加载页面。
使用它的好处是,如果稍加修改(将jQuery转换为Javascript),您不需要任何外部库或插件即可使用它。此外,这是非常简单和可以理解的。
ANOTHER OPTION ------------------------------------------- -
更高级一点,包含jQuery库&插件是必需的,但具有百分比功能。
检查出http://malsup.com/jquery/form/#file-upload的文档和完整的规范,这里演示:http://malsup.com/jquery/form/progress.html。
下面是代码:
<form action="zip-upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="zip_file">
<input type="submit" value="Upload">
</form>
<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);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
而且你的PHP页面上:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['zip_file']['name']);
if(move_uploaded_file($_FILES['zip_file']['tmp_name'], $target_path)) {
echo "The file ". basename($_FILES['zip_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>