进度条文件上传(只支持一般文件上传)
编写一个文件upload.html上传的表单,并使用FormData收集上传文件信息。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title></title>
<script type="text/javascript">
//通过页面加载事件实现上传文件时显示进度条
function sub(){
//实例化Ajax对象
var obj = new XMLHttpRequest();
//接收响应的信息
obj.onreadystatechange = function(){
if(obj.readyState==4 && obj.status==200){
if(obj.responseText){
document.getElementById('con').innerHTML = "文件上传成功";
}else{
document.getElementById('com').innerHTML = "文件上传失败";
}
}
}
//onprogress属性通过主流浏览器的“事件对象evt”感知当前附件上传情况
obj.upload.onprogress = function(evt){
//上传附件大小的百分比
//其中evt.total表示附件总大小,evt.loaded表示已经上传附件大小
var per = Math.floor((evt.loaded/evt.total)*100)+"%";
//当上传文件时,显示进度条
document.getElementById('parent').style.display = 'block';
//通过上传百分比设置进度条样式的宽度
document.getElementById('son').style.width = per;
//在进度条上显示上传的进度值
document.getElementById('son').innerHTML = per;
}
//通过FormData收集零散的上传文件信息
var fm = document.getElementById("userfile3").files[0];
//FormData()只有主流浏览器才支持
var fd = new FormData();
fd.append("userfile",fm);
obj.open('POST','upload.php',true);
obj.send(fd);
}
</script>
<style type="text/css">
#parent{width:200px;height:20px;border: 2px solid gray;background:lightgray;
display: none;}
#son{width:0;height:100%;background:lightgreen;text-align:center;}
</style>
</head>
<body>
<h2>Ajax实现进度条文件上传</h2>
<div id="parent">
<div id="son"></div>
</div>
<p id="con"></p>
<input type="file" name="userfile" id="userfile3"><br /><br />
<input type="button" onclick="sub()" value="文件上传"/>
</body>
编写服务器处理文件upload.php处理上传文件信息
<?php
//上传文件进行简单错误过滤
if($_FILES['userfile']['error']>0){
exit('上传文件有错误');
}
//定义存放上传文件的真实路径
$path = ".\\";
//定义存放上传文件的真实路径名
$name = $_FILES['userfile']['name'];
//将文件的名字的字符编码从UTF-8转换成GB2312
$name = iconv("UTF-8","GBK",$name);
//将上传文件移动到指定目录文件中
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$path.$name)){
//表示文件上传成功
echo 1;
}else{
//表示文件上传失败
echo 0;
}
?>