下载地址:http://download.csdn.net/detail/guoxuepeng123/5507987
所需Jar包:commons-fileupload.jar commons-io.jar
页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="<%=basePath%>/js/jquery-1.4.4.min.js"></script> <style type="text/css"> iframe{ border:none; width:0; height:0; } #progress{ display:none; } #p_out{ width:300px; height:12px; margin:10px 0 0 0; padding:1px; font-size:10px; border:solid #6b8e23 1px; } #p_in{ width:0%; height:100%; background-color:#6b8e23; margin:0; padding:0; } #dis{ margin:0; padding:0; text-align:center; font-size:12px; height:12px; width:300px; } </style> <script type="text/javascript"> var inter = null; function formSubmit(){ $("#progress").show(); inter = window.setInterval("callback();", 100);//每隔100毫秒执行callback document.getElementById('dis').innerHTML = "初始化数据..."; document.getElementById('p_in').style.width = "0%"; document.form.submit(); } function callback(){ $.ajax({ url: "<%=basePath%>/uploadStatus", type: "POST", async:false, data: { }, error:function(errorMsg){ }, success: function(data){ document.getElementById('dis').innerHTML = '已上传:'+data; document.getElementById('p_in').style.width = data; if(data.indexOf("100%")!=-1){ uploadSuccess(); } } }); } function uploadSuccess(){ clearInterval(inter); document.getElementById('dis').innerHTML = "上传成功!"; document.getElementById('p_in').style.width = "100%"; } </script> </head> <body> <form action="<%=basePath%>/upload" method="post" enctype="multipart/form-data" target="progress_iframe" name="form" > <input type="file" name="file" ><input type="button" onclick="formSubmit();" value="提交"> </form> <iframe frameborder="0" id="progress_iframe" name="progress_iframe" src="javascript:void(0)"></iframe> <div id="progress"> <div id="p_out"><div id="p_in"> </div></div> <div id="dis"></div> </div> </body> </html>
Servlet
文件上传处理Servlet UploadServlet.java
package com.fileupload.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import com.fileupload.entity.FileUpload; public class UploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String key = Integer.toString(request.hashCode()); request.getSession().setAttribute("key", key); PrintWriter out = response.getWriter(); FileUpload fu=new FileUpload(); fu.setMap(request,key);//解析request Map<String,FileItem> files=fu.getFiles(); String fileName =fu.getFileName(files.get("file")); File file=new File(this.getServletContext().getRealPath("upload\\"+fileName)); try { files.get("file").write(file); } catch (Exception e) { e.printStackTrace(); } out.println("<script>parent.uploadSuccess();</script>"); } }
实时获取上传状态Servlet UploadStatusServlet.java
package com.fileupload.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 UploadStatusServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(); String key = (String) request.getSession().getAttribute("key"); String status=(String) session.getAttribute(key);//获取上传进度百分比 out.println(status);//响应 } }
文件上传进度信息类 Progress.java
package com.fileupload.entity; import java.text.NumberFormat; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.ProgressListener; /** * 上传文件进度信息 * */ public class Progress implements ProgressListener { private HttpSession session; private long length = 0; private long currentLength = 0; private boolean isComplete = false; private double megaBytes = -1; private String key; public Progress(HttpServletRequest request,String key) { session = request.getSession(); this.key = key; } public void update(long pBytesRead, long pContentLength, int items) { this.currentLength = pBytesRead; double mBytes = pBytesRead / 1000000; double total=pContentLength/1000000; if (megaBytes == mBytes) { return; } // System.out.println("total====>"+total); // System.out.println("mBytes====>"+mBytes); megaBytes = mBytes; // System.out.println("megaBytes====>"+megaBytes); // System.out.println("We are currently reading item " + items); if (pContentLength == -1) { // System.out.println("So far, " + pBytesRead + " bytes have been read."); } else { // System.out.println("So far, " + pBytesRead + " of " + pContentLength // + " bytes have been read."); double read=(mBytes/total); NumberFormat nf=NumberFormat.getPercentInstance(); // System.out.println("read===>"+nf.format(read));//生成读取的百分比 并放入session中 session.setAttribute(key, nf.format(read)); } } public long getLength() { return length; } public long getCurrentLength() { return currentLength; } public boolean isComplete() { return isComplete; } public void setLength(long length) { this.length = length; } public void setCurrentLength(long currentLength) { this.currentLength = currentLength; } public void setComplete(boolean isComplete) { this.isComplete = isComplete; } }
文件上传封装类 FileUpload.java
package com.fileupload.entity; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUpload { private Map<String,String> params; private Map<String,FileItem> files; public FileUpload() { params=new HashMap<String, String>(); files=new HashMap<String, FileItem>(); } public void setMap(HttpServletRequest request,String key){ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); upload.setProgressListener(new Progress(request,key));//设置进度监听器 try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); params.put(name, value); } else{ String name=item.getFieldName(); files.put(name, item); } } } catch (FileUploadException e) { e.printStackTrace(); } } public Map<String, String> getParams() { return params; } public Map<String, FileItem> getFiles() { return files; } //用来获取文件的名字 public String getFileName(FileItem item){ String fName=item.getName(); int lastIndex=fName.lastIndexOf("\\"); fName=fName.substring(lastIndex+1); return fName; } }