基于ajax实现文件上传并显示进度条
网络编程 2021-07-04 21:48www.168986.cn编程入门
这篇文章主要介绍了基于ajax实现文件上传并显示进度条,需要的朋友可以参考下
狼蚁网站SEO优化给大家分享下基于ajax实现文件上传并显示进度条。在jsp部分,需要设计一个表单,form的属性添加 enctype="multipart/form-data",设计一个iframe,作为隐藏。form的target等于iframe的name;
在servlet部分文件上传用的Commons-FileupLoad,需要两个Jar,mons-fileupload和mons-io,少了第二个会报出找不到类的异常;
第一个servlet处理上传,及把上传进度保存到session,第二个servlet处理ajax请求,回传session保存的进度值;
进度条可以用ajax拿到回传的进度值,改变图片的width实现变化;
jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://.w3./TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="css/progress.css"> <script type="text/javascript" src="js/ul.js" charset="gbk"></script> </head> <body> <form action="UploadServlet" name="f1" id="f1" method="post" enctype="multipart/form-data" target="if"> <input type="file" name="file1" /><br><br> <input type="reset" name="res1" value="重置"/> <input type="button" name="but1" value="提交" onclick="go();"/> </form><br> <div id="pro" class="pro" align="left"> <img alt="" src="photo/progress.png" width="0" height="15" id="imgpro"> </div> <span id="prop" style="width:15px;height:15px;display: none;">0%</span> <iframe id="if" name="if" src="" style="display: none"></iframe> </body> </html>
这是index.jsp里的代码
提交后还在当前页显示进度,所以要用到iframe,提交后的返回放到隐藏的iframe里,不影响页面效果;
css代码
代码如下:
.pro{
height:15px;
width:500px;
background: #FFFFF0;
border: 1px solid #8FBC8F;
margin: 0;
padding: 0;
display:none;
position: relative;
left:25px;
float:left;
}
js代码
function go(){ f1.submit(); document.getElementById("pro").style.display="block"; document.getElementById("prop").style.display=""; timer=setInterval("getP()",50); } var xmlHttpRequest; function getP(){ if(window.XmlHttpRequest){ xmlHttpRequest=new XmlHttpRequest(); }else{ xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttpRequest.onreadystatechange=callBack; url="getProgressServlet"; xmlHttpRequest.open("post",url,true); xmlHttpRequest.setRequestHeader("Content-type","application/x--form-urlencoded"); xmlHttpRequest.send("&timeStamp="+(new Date()).getTime()); } //回调函数 function callBack(){ if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){ result=xmlHttpRequest.responseText; var result=result.replace(/(^\s)|(\s$)/g, ""); var res=result.split(","); var flag=res[1]; var per=parseInt(res[0]); var err=res[2]; document.getElementById("imgpro").style.width=per5+"px"; document.getElementById("prop").innerHTML=per+"%"; if(flag=="OK"){ window.clearInterval(timer); alert("上传成功!"); document.getElementById("pro").style.display="none"; document.getElementById("prop").innerHTML=""; f1.reset(); } if(err!=""||err.length>0){ window.clearInterval(timer); alert(err); } if(flag==null){ window.clearInterval(timer); } } }
flag为上传成功标记,err为出错标记;
servlet代码(UploadServlet)
package .ul.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import .apache.mons.fileupload.FileItem; import .apache.mons.fileupload.disk.DiskFileItemFactory; import .apache.mons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码格式为utf-8 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //获取session,保存进度和上传结果,上传结果初始值为NOK,当为Ok表示上传完成 HttpSession session=request.getSession(); session.setAttribute("prog", "0"); session.setAttribute("result", "NOK"); session.setAttribute("error", ""); String error=""; //给上传的文件设一个最大值,这里是不得超过50MB int maxSize=5010241024; //创建工厂对象和文件上传对象 DiskFileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(factory); try { //解析上传请求 List items=upload.parseRequest(request); Iterator itr=items.iterator(); while(itr.hasNext()){ FileItem item=(FileItem)itr.next(); //判断是否为文件域 if(!item.isFormField()){ if(item.getName()!=null&&!item.getName().equals("")){ //获取上传文件大小和文件名称 long upFileSize=item.getSize(); String fileName=item.getName(); if(upFileSize>maxSize){ error="您上传的文件太大了,请选择不超过50MB的文件!"; break; } //此时文件暂存在服务器的内存中,构造临时对象 File tempFile=new File(fileName); //指定文件上传服务器的目录及文件名称 File file=new File("f:\\temp",tempFile.getName()); //构造输入流读文件 InputStream is=item.getInputStream(); int length=0; byte[] by=new byte[1024]; double persent=0; FileOutputStream fos=new FileOutputStream(file); PrintWriter out=response.getWriter(); while((length=is.read(by))!=-1){ //计算文件进度 persent+=length/(double)upFileSize100D; fos.write(by, 0, length); session.setAttribute("prog", Math.round(persent)+""); Thread.sleep(10); } fos.close(); Thread.sleep(1000); }else{ error="没选择上传文件!"; } } } } catch (Exception e) { e.printStackTrace(); error="上传文件出现错误:"+e.getMessage(); } if(!error.equals("")){ session.setAttribute("error", error); }else{ session.setAttribute("result", "OK"); } } }
不要忘记mons-io包
servlet代码(getProgressServlet)
package .ul.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class getProgressServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); HttpSession sesson=request.getSession(); PrintWriter out=response.getWriter(); String str=(String)sesson.getAttribute("prog")+""; String res=(String)sesson.getAttribute("result"); String err=(String)sesson.getAttribute("error"); System.out.println(str+","+res+","+err); out.print(str+","+res+","+err); out.flush(); out.close(); } }
效果图如下
以上就是本文的全部内容,希望对大家有所帮助。
编程语言
- 如何快速学会编程 如何快速学会ug编程
- 免费学编程的app 推荐12个免费学编程的好网站
- 电脑怎么编程:电脑怎么编程网咯游戏菜单图标
- 如何写代码新手教学 如何写代码新手教学手机
- 基础编程入门教程视频 基础编程入门教程视频华
- 编程演示:编程演示浦丰投针过程
- 乐高编程加盟 乐高积木编程加盟
- 跟我学plc编程 plc编程自学入门视频教程
- ug编程成航林总 ug编程实战视频
- 孩子学编程的好处和坏处
- 初学者学编程该从哪里开始 新手学编程从哪里入
- 慢走丝编程 慢走丝编程难学吗
- 国内十强少儿编程机构 中国少儿编程机构十强有
- 成人计算机速成培训班 成人计算机速成培训班办
- 孩子学编程网上课程哪家好 儿童学编程比较好的
- 代码编程教学入门软件 代码编程教程