基于HTML5 Ajax实现文件上传并显示进度条
前端  /  管理员 发布于 4年前   261
本文实例讲解了ajax上传文件及进度条的实现方法,分享给大家供大家参考,具体内容如下
效果图:
html5上传是同步上传的方式,所以能够实现进度条的显示。
1.上传文件:
首先我们用ajax来取得<input type="file" id="file_upload">的file对象:
var file = null; var input = $("#file_upload"); //文件域选择文件时, 执行readFile函数 input.addEventListener('change',readFile,false); function readFile(){ file = this.files[0]; }
然后用FormData()送到后台。
var fd = new FormData(); fd.append("file", file);
2.监听事件:给XMLHttpRequest添加上传中的监听事件,可以得到已上传的文件大小,用以实现进度条的显示。
//监听事件 hr.upload.addEventListener("progress", uploadProgress, false);
完整代码如下:
<html> <head> <meta charset="utf-8"> <title>进度条测试</title> <script type="text/javascript" src="//article/../js/jquery-1.11.1.min.js"></script> </head> <body> <input type="file" id="file_upload"/> <input type="button" value="上传" id="upload"/> <div style="background:#848484;width:100px;height:10px;margin-top:5px"> <div id="progressNumber" style="background:#428bca;width:0px;height:10px" > </div> </div> <font id="percent">0%</font> </body> <script> var file = null; $(function(){ $("#upload").click(function(){ upload(); }); }); var input = document.getElementById("file_upload"); //文件域选择文件时, 执行readFile函数 input.addEventListener('change',readFile,false); function readFile(){ file = this.files[0]; } //上传文件 function upload(){ var xhr = new XMLHttpRequest(); var fd = new FormData(); fd.append("fileName", file); //监听事件 xhr.upload.addEventListener("progress", uploadProgress, false); //发送文件和表单自定义参数 xhr.open("POST", "../UploadServlet",true); xhr.send(fd); } function uploadProgress(evt){ if (evt.lengthComputable) { //evt.loaded:文件上传的大小 evt.total:文件总的大小 var percentComplete = Math.round((evt.loaded) * 100 / evt.total); //加载进度条,同时显示信息 $("#percent").html(percentComplete + '%') $("#progressNumber").css("width",""+percentComplete+"px"); } } </script> </html>
以上就是关于ajax实现带进度条的文件上传全部内容,希望对大家的学习有所帮助。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号