上传带进度条
package com.upload; /** * 自定义文件上传监听器 */ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.ProgressListener; public class MyProcessLister implements ProgressListener{ HttpSession session; public MyProcessLister(HttpServletRequest request) { session = request.getSession(); session.setAttribute("status", 0); session.setAttribute("times", 1); } @Override public void update(long read, long total, int times) { int precent = (int) (read*100/total); session.setAttribute("status", precent); session.setAttribute("times", times); } }
package com.upload; /** * 刷新进度 */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; @SuppressWarnings("serial") @WebServlet("/upload/process") public class RefreshProcess extends HttpServlet { public void doPost(HttpServletRequest request ,HttpServletResponse response) throws IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html;charset=utf-8"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); if (null == session.getAttribute("status")) { session.setAttribute("status", 0); session.setAttribute("times", 1); } JSONObject json = new JSONObject(); json.put("status", session.getAttribute("status")); json.put("times", session.getAttribute("times")); out.print(json); out.close(); } }
package com.upload; /*** * 文件上传
<script type="text/javascript" src="${path}/js/jquery.js" ></script> <script type="text/javascript" src="${path}/js/bootstrap.min.js" ></script> <script type="text/javascript"> $("#bt").click(function(){ tForm(); // 提交表单 setInterval(procesfun,1000); // 定时任务 }); // 提交form表单 function tForm(){ var form = new FormData(document.getElementById("tf")); $.ajax({ url:"${path}/servlet/UploadServlet", type:"post", data:form, processData:false, contentType:false, success:function(data){ console.log(data); }, error:function(e){ $("#result").html("用户取消了上传操作").css("color","red"); } }); }; // 定时请求上传进度 function procesfun(){ $.ajax({ type:"post", url:"${path}/upload/process", success:function(data){ var obj = eval('(' + data + ')'); if ("1" == obj.times){ $("#result").html("身份证正面正在上传,上传进度为:"+obj.status+"%,请耐心等待。").css("color","red"); } if ("2" == obj.times){ $("#result").html("身份证反面正在上传,上传进度为:"+obj.status+"%,请耐心等待。").css("color","red"); } if ("3" == obj.times){ $("#result").html("手持身份证正在上传,上传进度为:"+obj.status+"%,请耐心等待。").css("color","red"); if("100" == obj.status){ $("#result").html("文件上传成功。").css("color","red"); window.setTimeout("window.location='${path}/uploadSuccess.jsp'",2000); } } }, error:function(){ $("#result").html("用户取消了上传操作").css("color","red"); } }) } function checkFile(){ var zm = document.getElementById("zm").value; var fm = document.getElementById("fm").value; var sc = document.getElementById("sc").value; if ("" == zm || null ==zm){ alert("身份证正面不能为空。"); return false; } if ("" == fm || null ==fm){ alert("身份证反面不能为空。"); return false; } if ("" == sc || null ==sc){ alert("手持身份证不能为空。"); return false; } }; function info(){ alert("上传用户信息可能需要一分钟左右,请耐心等待。"); } </script>
*/ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.StringUtils; import org.apache.commons.mail.EmailException; import com.email.SendMailUtil; import com.model.SqlContext; import com.sql.Conn; @SuppressWarnings("serial") @WebServlet(value="/servlet/UploadServlet") public class UpLoadServlet extends HttpServlet { @SuppressWarnings("null") public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html;charset=utf-8"); PrintWriter write = response.getWriter(); String savePath = this.getServletContext().getRealPath("/upload"); StringBuffer sb = new StringBuffer(); File saveFileDir = new File(savePath); if (!saveFileDir.exists()) { // 创建临时目录 saveFileDir.mkdirs(); } String tmpPath = this.getServletContext().getRealPath("/temp"); File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { // 创建临时目录 tmpFile.mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); MyProcessLister listener = new MyProcessLister(request);// 在文件上传至流时进行文件监听 upload.setProgressListener(listener);// 注册监听 try { List<FileItem> items = upload.parseRequest(request); Iterator<?> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (!item.isFormField()) // 如果为非文件类型数据 { String fileName = item.getName(); if (null == fileName && 0 == fileName.trim().length()) { continue; } // 文件名和文件后缀名 fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); String saveFileName = UUID.randomUUID().toString()+"."+fileExt; InputStream is = item.getInputStream(); //创建一个文件输出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + saveFileName); sb.append(saveFileName); sb.append(";"); byte buffer[] = new byte[1024]; //判断输入流中的数据是否已经读完的标致 int len = 0; while((len = is.read(buffer)) > 0) { out.write(buffer, 0, len); } //关闭输出流 out.close(); //关闭输入流 is.close(); //删除临时文件 item.delete(); } } } catch (FileUploadException e) { System.out.println("throws FileUploadException."); } catch (IOException e) { System.out.println("throw IOException."); } } }