用commons-fileupload-1.2 实现文件上传
1.首先,记得导入tomcat下的jar包
jsp代码 uploadSS.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>upload</title> </head> <body> <form action="FileUploadServlet" method="post" enctype="multipart/form-data"> <input type="file" size="30" name="test" /> <br /> <input name="up" type="submit" value="上传" /> </form> </body> </html>
然后编写此页面跳转的servlet
1 package com.netcloud.upload; 2 import java.io.File; 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.Iterator; 6 import java.util.List; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 import org.apache.commons.fileupload.FileItem; 14 import org.apache.commons.fileupload.FileUploadException; 15 import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; 16 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 17 import org.apache.commons.fileupload.servlet.ServletFileUpload; 18 //测试成功 19 public class FileUploadServlet extends HttpServlet { 20 21 public FileUploadServlet() { 22 super(); 23 } 24 25 public void destroy() { 26 super.destroy(); // Just puts "destroy" string in log 27 // Put your code here 28 } 29 30 public void doGet(HttpServletRequest request, HttpServletResponse response) 31 throws ServletException, IOException { 32 doPost(request, response); 33 } 34 35 public void doPost(HttpServletRequest request, HttpServletResponse response) 36 throws ServletException, IOException { 37 final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M 38 // 允许上传的文件格式的列表 39 final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "txt", 40 "doc", "docx", "mp3", "wma", "m4a" }; 41 response.setContentType("text/html"); 42 // 设置字符编码为UTF-8, 这样支持汉字显示 43 response.setCharacterEncoding("UTF-8"); 44 45 // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload 46 DiskFileItemFactory dfif = new DiskFileItemFactory(); 47 dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘 48 dfif.setRepository(new File(request.getRealPath("/") 49 + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录 50 51 // 用以上工厂实例化上传组件 52 ServletFileUpload sfu = new ServletFileUpload(dfif); 53 // 设置最大上传尺寸 54 sfu.setSizeMax(MAX_SIZE); 55 56 PrintWriter out = response.getWriter(); 57 // 从request得到 所有 上传域的列表 58 List fileList = null; 59 try { 60 fileList = sfu.parseRequest(request); 61 } catch (FileUploadException e) {// 处理文件尺寸过大异常 62 if (e instanceof SizeLimitExceededException) { 63 out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />"); 64 out.println("<a href=\"uploadSS.jsp\" target=\"_top\">返回</a>"); 65 return; 66 } 67 e.printStackTrace(); 68 } 69 // 没有文件上传 70 if (fileList == null || fileList.size() == 0) { 71 out.println("请选择上传文件<p />"); 72 out.println("<a href=\"uploadSS.jsp\" target=\"_top\">返回</a>"); 73 return; 74 } 75 // 得到所有上传的文件 76 Iterator fileItr = fileList.iterator(); 77 // 循环处理所有文件 78 while (fileItr.hasNext()) { 79 FileItem fileItem = null; 80 String path = null; 81 long size = 0; 82 // 得到当前文件 83 fileItem = (FileItem) fileItr.next(); 84 // 忽略简单form字段而不是上传域的文件域(<input type="text" />等) 85 if (fileItem == null || fileItem.isFormField()) { 86 continue; 87 } 88 // 得到文件的完整路径 89 path = fileItem.getName(); 90 // 得到文件的大小 91 size = fileItem.getSize(); 92 if ("".equals(path) || size == 0) { 93 out.println("请选择上传文件<p />"); 94 out.println("<a href=\"uploadSS.jsp\" target=\"_top\">返回</a>"); 95 return; 96 } 97 98 // 得到去除路径的文件名 99 String t_name = path.substring(path.lastIndexOf("\\") + 1); 100 // 得到文件的扩展名(无扩展名时将得到全名) 101 String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); 102 // 拒绝接受规定文件格式之外的文件类型 103 int allowFlag = 0; 104 int allowedExtCount = allowedExt.length; 105 for (; allowFlag < allowedExtCount; allowFlag++) { 106 if (allowedExt[allowFlag].equals(t_ext)) 107 break; 108 } 109 if (allowFlag == allowedExtCount) { 110 out.println("请上传以下类型的文件<p />"); 111 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++) 112 out.println("*." + allowedExt[allowFlag] 113 + " "); 114 out.println("<p /><a href=\"uploadSS.jsp\" target=\"_top\">返回</a>"); 115 return; 116 } 117 118 long now = System.currentTimeMillis(); 119 // 根据系统时间生成上传后保存的文件名 120 String prefix = String.valueOf(now); 121 // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下 122 String u_name = request.getRealPath("/") + "ImagesUploaded/" 123 + prefix + "." + t_ext; 124 try { 125 // 保存文件 126 fileItem.write(new File(u_name)); 127 out.println("文件上传成功. 已保存为: " + prefix + "." + t_ext 128 + " 文件大小: " + size + "字节<p />"); 129 out.println("<a href=\"uploadSS.jsp\" target=\"_top\">继续上传</a>"); 130 } catch (Exception e) { 131 e.printStackTrace(); 132 } 133 } 134 135 } 136 137 public void init() throws ServletException { 138 // Put your code here 139 } 140 141 }
注意新建servlet生成的web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>TestLearn</display-name> <servlet> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>com.netcloud.upload.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/FileUploadServlet</url-pattern> </servlet-mapping> </web-app>
注意:servlet提到的ImagesUploaded ImagesUploadTemp二个文件夹要放在tomcat的目录下
如D:\apache-tomcat-7.0.23\wtpwebapps\TestLearn
2.这是另外一种看起来比较简洁但是实际上跟第一种一样原理的方法:
<%@ 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>→uploadServlet→redult.jsp</title> </head> <body> <form action="uploadServlet" method="POST" enctype="multipart/form-data" > upload:<input type="file" name="text" size="30"/> <input type="submit" value="view>>>"> </form> </body> </html>
跳转的servlet
package com.netcloud.upload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; 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 org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * 文件上传如果文件小,上传组件可以将文件存放在内存中, * 如果过大时会放在临时目录里面,之后再通过IO流操作 * @author LEPING LI * */ @SuppressWarnings("unchecked") public class uploadServlet extends HttpServlet{ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //磁盘文件条目工厂 DiskFileItemFactory factory=new DiskFileItemFactory(); // 文件上传如果文件小,上传组件可以将文件存放在内存中, //如果过大时会放在临时目录里面,之后再通过IO流操作 //获取目录真实路径 / 代表 WebRoot目录下面 String path=request.getRealPath("/"); //设置临时目录 factory.setRepository(new File(path)); //设置上传文件大小 factory.setSizeThreshold(1024*1024); //创建一个ServletFileUpload 实例 ServletFileUpload sfu=new ServletFileUpload(factory); try { //解析请求,取得FileItem 列表 List<FileItem> lis=sfu.parseRequest(request); //循环遍历 for(FileItem item:lis){ //判断是否是简单的表单字段 if(item.isFormField()){ String name=item.getFieldName(); String value=item.getString("UTF-8"); request.setAttribute(name, value); }else{ //取得字段名 String name=item.getFieldName(); // 取得文件路径名 String value=item.getName(); System.out.println("value:"+value); //为了屏蔽各个浏览器提供的路径不同异常 int start=value.lastIndexOf("//"); //取得文件名 String fileName=value.substring(start+1); request.setAttribute(name, fileName); item.write(new File(path,fileName)); //这句代码与下面高亮显示的代表功能相同 //获取文件输出流 File f=new File(path,fileName); OutputStream os=new FileOutputStream(f); //获取文件条目的输入流 InputStream in=item.getInputStream(); byte[] buffer=new byte[400]; int length=0; //读写文件 while((length=in.read(buffer))>0){ os.write(buffer,0,length); } os.flush(); os.close(); in.close(); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.getRequestDispatcher("result.jsp").forward(request, response); } }
servlet跳转的result.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> </head> <body> 文件目录:${requestScope.text }<br> </body> </html>