strburnchang 2011-07-26
使用了commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar两个组件。
后台UploadServlet.java:
package upload; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings("rawtypes") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); StringBuilder msg = new StringBuilder(); final long maxSize = 1000 * 1024 * 1024; final String[] suffix = new String[] {"jpg", "jpeg", "gif", "txt", "doc","mp3", "wma", "m4a","rar","zip"}; File tmpdir = new File("c:/tmpdir"); if (!tmpdir.exists()) { tmpdir.mkdirs(); } File uploaddir = new File("c:/uploaddir"); if (!uploaddir.exists()) { uploaddir.mkdirs(); } DiskFileItemFactory fac = new DiskFileItemFactory(1024*4, tmpdir); ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List fileList = null; try { fileList = upload.parseRequest(request); } catch (FileUploadException e) { if (e instanceof SizeLimitExceededException) { out.println("<script>parent.callback('" + " 文件尺寸超过 " + maxSize + " 最大限制 " + "')</script>"); return; } e.printStackTrace(); } if (fileList.size() > 0) { for (Iterator it = fileList.iterator(); it.hasNext();) { String path = ""; String filename = null; long size = 0; String fileSuffix = null; boolean has = false; FileItem item = (FileItem) it.next(); if (item == null || item.isFormField()) { continue; } path = item.getName(); int temp = path.lastIndexOf("\\"); filename = temp != -1 ? path.substring(temp + 1) : path; size = item.getSize(); if (!path.equals("") && size != 0) { fileSuffix = path.substring(path.lastIndexOf(".") + 1); for (String s : suffix) { if (s.equals(fileSuffix)) { has = true; break; } } if (!has) { msg.append(filename + " 上传文件格式不正确 "); continue; } try { item.write(new File(uploaddir + File.separator + filename)); msg.append(filename + " 上传成功 "); } catch (Exception e) { msg.append(filename + " 上传失败 "); e.printStackTrace(); } } } } out.println("<script>parent.callback('" + msg.toString() + "')</script>"); } }
jsp文件上传页面:
<%@ 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"> function callback(msg) { /* document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;*/ document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>"; } </script> </head> <body> <form action="<%=path %>/UploadServlet" id="form1" name="form1" encType="multipart/form-data" method="post" target="hidden_frame" > <input type="file" id="file" name="file" style="width:450"><br> <input type="file" id="file" name="file" style="width:450"><br> <input type="file" id="file" name="file" style="width:450"><br> <input type="file" id="file" name="file" style="width:450"><br> <input type="file" id="file" name="file" style="width:450"><br> <input type="file" id="file" name="file" style="width:450"><br> <INPUT type="submit" value="上传文件"><span id="msg"></span><br> <font color="red">支持"jpg", "jpeg", "gif", "txt", "doc","mp3", "wma", "m4a","rar","zip"文件的上传</font> <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe> </form> </body> </html>