Rumah > Artikel > hujung hadapan web > Laksanakan muat naik fail dan paparkan bar kemajuan berdasarkan kemahiran ajax_javascript
下面给大家分享下基于ajax实现文件上传并显示进度条。在jsp部分,需要设计一个表单,form的属性添加 enctype="multipart/form-data",设计一个iframe,作为隐藏。form的target等于iframe的name;
在servlet部分:文件上传用的Commons-FileupLoad,需要两个Jar,commons-fileupload和commons-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://www.w3.org/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代码:
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-www-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=per*5+"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 com.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 org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.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=50*1024*1024; //创建工厂对象和文件上传对象 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)upFileSize*100D; 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"); } } }
不要忘记commons-io包
servlet代码(getProgressServlet):
package com.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(); } }
效果图如下:
以上就是本文的全部内容,希望对大家有所帮助。