上传时显示进度条

上传时使用common-fileupload,如果实现了ProgressListener接口,将进度信息保存到session中,这样可以随时了解上传的进度情况。进度条使用了一现成的jquery.progressbar。

上传图片时要预览图片,考虑到浏览器不兼容问题,最好是将图片上传到服务器,获取图片的服务器路径,通过session(将上传图片路径保存到session中)或者是其它的方式。不过要记得后续的上传要删除之前已上传到服务器的图片文件。

进度监听器

** * @author Evan 进度监听器 * */ public class CustomerProgressListener implements ProgressListener { private HttpServletRequest request; public CustomerProgressListener(HttpServletRequest request) { this.request = request; } @Override public void update(long bytesRead, long contentLength, int items) { // 将百分比保存到session中 double percentage = ((double) bytesRead / (double) contentLength); HttpSession session = this.request.getSession(); session.setAttribute("percentage", percentage); } }

上传servlet

/** * @author Evan 上传servlet * */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = -2720594804583840761L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try{ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //设置进度监听 upload.setProgressListener(new CustomerProgressListener(req)); List items = upload.parseRequest(req); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()){ } else { //String fieldName = item.getFieldName(); String fileName = item.getName(); //String contentType = item.getContentType(); System.out.println(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File("H://" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."))); item.write(uploadedFile); } } }catch(Exception e){ e.printStackTrace(); } resp.getWriter().print("{msg:'上传成功!'}"); resp.getWriter().flush(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }

进度servlet

public class ProgressServlet extends HttpServlet { private static final long serialVersionUID = 8057160912240634296L; //获取上传进度情况 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(); Double percentage=0.0; if(session.getAttribute("percentage")!=null){ percentage=(Double)session.getAttribute("percentage"); double retVal=Math.floor(percentage*100); if(retVal == 100.0D){ session.removeAttribute("percentage"); } out.print("{retVal:"+retVal+"}"); }else{ out.print("{retVal:-1.0}"); } } }

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 上传Demo


你可能感兴趣的:(Java,开发)