您当前的位置: 首页 > 学无止境 > CSS3|Html5 网站首页CSS3|Html5
原生ajax与html5实现文件上传(带进度条)
发布时间:2016-08-21 12:45:54编辑:雪饮阅读()
本demo使用了原生的ajax与html5的上传监控事件,该事件可以在控制台consle.log函数中查看对象属性等信息。
前端:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script type="text/javascript">
function selfile(){
document.getElementById("up").style.display="block";
}
function up(){
//创建formdata对象
var fd=new FormData();
//获取文件对象
var pic=document.getElementsByTagName('input')[0].files[0];
//把文件内容追加到表单数据里
fd.append(0,pic);//0为文件数组files中第一个文件的键名字,后端取该文件如:$_FILES[0][tmp_name]
var xhr=new XMLHttpRequest();
xhr.open('POST','02.php',true);//ajax提交虽然为post,但后端中要在files数组中才能获取,若获取post信息则为空数组
document.getElementById("box").style.display="block";
document.getElementById("up").style.display="none";
xhr.onreadystatechange=function (){
if(this.readyState==4){
alert(this.responseText);
}
}
//上传监控事件,当文件上传事件发生时,会将该事件的信息以参数的形式传递到其后的回调函数中。
xhr.upload.onprogress=function (ev){
if(ev.lengthComputable){
var percent=100*ev.loaded/ev.total;
console.log(percent);
document.getElementById("bar").style.width=percent+'%';
}
}
xhr.send(fd);
}
</script>
</head>
<body>
<input type="file" name="pic" onChange="selfile();"/>
<div id='box' style="width:500px;height:40px;border:1px solid red;display:none;">
<div id="bar" style="width:0px; background:pink;height:40px;"></div>
</div>
<input type="button" onClick="up();" value="上传" id="up" style="display:none"/>
</body>
</html>
关键字词:ajax,html5,上传