1 在javaweb开发中,文件的上传和下载是经常要用到的功能,为客户提供更好的便捷。
2 对于文件上传,浏览器上传文件的过程中是将文件以流的形式上传到服务器中的,如果直接用servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件。common-fileupload是依赖于common-io这个包的,所以还需要下载这个包。
3开发环境的搭建,导入两个jar包。
4 代码实现文件的上传方式
a 写一个upload.jsp上传的页面,这里表单的类型为enctype="multipart/form-data"
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 <form action="${pageContext.request.contextPath }/uploadServlet" method="post" enctype="multipart/form-data" > 25 文件:<input type="file" name="file1"><br> 26 <input type="submit" value="提交"> 27 28 </form> 29 </body> 30 </html>
b 在后台编写servlet类来实现逻辑代码
1 package fileUpload; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.PrintWriter; 8 import java.util.List; 9 import java.util.UUID; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 import org.apache.commons.fileupload.FileItem; 17 import org.apache.commons.fileupload.FileUploadBase; 18 import org.apache.commons.fileupload.FileUploadException; 19 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 20 import org.apache.commons.fileupload.servlet.ServletFileUpload; 21 22 public class CopyOfUploadServlet extends HttpServlet { 23 public void doGet(HttpServletRequest request, HttpServletResponse response) 24 throws ServletException, IOException { 25 doPost(request, response); 26 } 27 28 public void doPost(HttpServletRequest request, HttpServletResponse response) 29 throws ServletException, IOException { 30 // 设置上传文件的保存目录 31 String path = "E://content"; 32 File file = new File(path); 33 // 判断文件目录是否存在 34 if (!file.exists() && !file.isDirectory()) { 35 System.out.println(path + "目录不存在,现在去建一个目录"); 36 // 创建目录 37 file.mkdir(); 38 } 39 // 反馈的消息 40 String message = null; 41 // 创建一个DiskFileItemFactory工厂 42 DiskFileItemFactory factory = new DiskFileItemFactory(); 43 // 创建一个文件解析器 44 ServletFileUpload upload = new ServletFileUpload(factory); 45 // 设置上传文件的编码 46 upload.setHeaderEncoding("utf-8"); 47 // 判断上传的是普通表单的数据还是带文件的表单数据 48 if (!ServletFileUpload.isMultipartContent(request)) { 49 return; 50 } 51 try { 52 upload.setFileSizeMax(1024 * 1024);// 设置单个文件的最大值,1024*1024也就是1MB 53 upload.setFileSizeMax(1024 * 1024 * 10);// 设置总的文件大小10MB 54 // 使用ServletFileUpload解析上传的数据,返回的是集合,每一个FileItem对应一个Form表单的输入项 55 List<FileItem> lists = upload.parseRequest(request); 56 // 遍历集合 57 for (FileItem list : lists) { 58 // 如果FileItem是普通表单数据 59 if (list.isFormField()) { 60 String name = list.getFieldName(); 61 // 设置编码 62 String value = list.getString("utf-8"); 63 // value=new String(value.getBytes("iso8859-1"),"utf-8"); 64 System.out.println(name + "=" + value); 65 } else { 66 // 如果FileItem封装的是带文件的表单 67 String filename = list.getName();// 得到文件名称 68 System.out.println(filename); 69 if (filename == null || filename.trim().equals("")) { 70 continue; 71 } 72 // 不同浏览器提交的文件名是不一样的,有的是带路径的,有的就是文件名,如如:c:a1.txt,而有些只是单纯的文件名,如:1.txt 73 // 处理文件名的路径部分 74 filename = filename.substring(filename.lastIndexOf("//") + 1); 75 String savaname=makeFileName(filename); 76 // 获取扩展名 77 String FileExName = filename.substring(filename.lastIndexOf(".") + 1); 78 System.out.println("上传的扩展名是" + FileExName); 79 // 获取输入流 80 InputStream in = list.getInputStream(); 81 // 创建一个文件输出流 82 FileOutputStream out = new FileOutputStream(path + "\"+ savaname); 83 // 创建一个缓冲区 84 byte[] buffer = new byte[1024]; 85 int length = 0; 86 // 如果读完了,当in.read()值等于-1时,代表数据读取完毕 87 while ((length = in.read(buffer)) > 0) { 88 out.write(buffer, 0, length); 89 } 90 // 关闭流 91 in.close(); 92 out.close(); 93 // 删除文件上传的临时文件 94 list.delete(); 95 message = "上传成功"; 96 } 97 } 98 } catch (FileUploadBase.FileSizeLimitExceededException e) { 99 e.printStackTrace(); 100 request.setAttribute("message", "单个文件超出最大值!!!"); 101 request.getRequestDispatcher("/success.jsp").forward(request,response); 102 return; 103 } catch (FileUploadBase.SizeLimitExceededException e) { 104 e.printStackTrace(); 105 request.setAttribute("message", "上传文件的总的大小超出限制的最大值!!!"); 106 request.getRequestDispatcher("/success.jsp").forward(request,response); 107 return; 108 } catch (Exception e) { 109 message = "文件上传失败!"; 110 e.printStackTrace(); 111 } 112 request.setAttribute("message", message); 113 request.getRequestDispatcher("/success.jsp").forward(request,response); 114 } 115 116 private String makeFileName(String filename){ 117 //为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名 118 return UUID.randomUUID().toString() + "_" + filename; 119 } 120 }
c 配置web.xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true"> 6 <servlet> 7 <description>This is the description of my J2EE component</description> 8 <display-name>This is the display name of my J2EE component</display-name> 9 <servlet-name>UploadServlet</servlet-name> 10 <servlet-class>fileUpload.CopyOfUploadServlet</servlet-class> 11 </servlet> 12 13 <servlet-mapping> 14 <servlet-name>UploadServlet</servlet-name> 15 <url-pattern>/uploadServlet</url-pattern> 16 </servlet-mapping> 17 18 </web-app>
5 前台展示