導入兩個jarcommons-fileupload.jar,和commons-io.jar
在請求中創建核心類
1 // 1. 創建工廠對象 2 FileItemFactory factory = new DiskFileItemFactory(); 3 // 2. 文件上傳核心工具類 4 ServletFileUpload upload = new ServletFileUpload(factory);
對上傳文件進行設置
// 設置大小限制參數 upload.setFileSizeMax(10*1024*1024); // 單個文件大小限制 upload.setSizeMax(50*1024*1024); // 總文件大小限制 upload.setHeaderEncoding("gbk"); // 對中文文件編碼處理
判斷是否是上傳文件
upload.isMultipartContent(request);//就是判斷enctype="multipart/form-data",如果enctype是multipart,那么就是一個上傳文件
下面獲取上傳request的數據封裝集合
List<FileItem> list = upload.parseRequest(request);
對FileItem遍歷和判斷
item.isFormField();判斷這個item是不是文件,還是說這個是表單項,真就是普通的文本數據,假就是文件
上傳代碼
/*********文件上傳組件: 處理文件上傳************/ try { // 1. 文件上傳工廠 FileItemFactory factory = new DiskFileItemFactory(); // 2. 創建文件上傳核心工具類 ServletFileUpload upload = new ServletFileUpload(factory); // 一、設置單個文件允許的最大的大小: 30M upload.setFileSizeMax(30*1024*1024); // 二、設置文件上傳表單允許的總大小: 80M upload.setSizeMax(80*1024*1024); // 三、 設置上傳表單文件名的編碼 // 相當於:request.setCharacterEncoding("UTF-8"); upload.setHeaderEncoding("UTF-8"); // 3. 判斷: 當前表單是否為文件上傳表單 if (upload.isMultipartContent(request)){ // 4. 把請求數據轉換為一個個FileItem對象,再用集合封裝 List<FileItem> list = upload.parseRequest(request); // 遍歷: 得到每一個上傳的數據 for (FileItem item: list){ // 判斷:普通文本數據 if (item.isFormField()){ // 普通文本數據 String fieldName = item.getFieldName(); // 表單中元素名稱 String content = item.getString(); // 表單中元素名稱里所對應的數據 //item.getString("UTF-8"); 指定編碼 System.out.println(fieldName + " " + content); } // 上傳文件(文件流) ----> 上傳到upload目錄下 else { // 普通文本數據 String fieldName = item.getFieldName(); // 表單中的元素名稱 String name = item.getName(); // 文件名,上傳文件的名稱 String content = item.getString(); // 表單元素名稱, 對應的數據,如果事文本就會返回文本,如果事二進制返回亂碼 String type = item.getContentType(); // 文件類型,是圖片,文本,壓縮包等 InputStream in = item.getInputStream(); // 上傳文件流 /* * 四、文件名重名 * 對於不同用戶readme.txt文件,不希望覆蓋! * 后台處理: 給用戶添加一個唯一標記! */ // a. 隨機生成一個唯一標記 String id = UUID.randomUUID().toString(); // b. 與文件名拼接 name = id +"#"+ name; // 獲取上傳基路徑 //String path = getServletContext().getRealPath("/upload"); String path = "e:\\upload"; // 創建目標文件 File file = new File(path,name); // 工具類,文件上傳 item.write(file); item.delete(); //刪除系統產生的臨時文件,這個是一個占內存的中轉數據,沒用,應該刪除 System.out.println(path); } } } else { System.out.println("當前表單不是文件上傳表單,處理失敗!"); } } catch (Exception e) { e.printStackTrace(); }
下載
首先需要獲取下載列表中的內容
如下servlet
// 實現思路:先獲取upload目錄下所有文件的文件名,再保存;跳轉到down.jsp列表展示 //1. 初始化map集合Map<包含唯一標記的文件名, 簡短文件名> ; Map<String,String> fileNames = new HashMap<String,String>(); //2. 獲取上傳目錄,及其下所有的文件的文件名 //String basePath = getServletContext().getRealPath("/upload"); String basePath = "e:\\upload"; // 目錄 File file = new File(basePath); // 目錄下,所有文件名 String list[] = file.list(); // 遍歷,封裝 if (list != null && list.length > 0){ for (int i=0; i<list.length; i++){ // 全名 String fileName = list[i]; // 短名 String shortName = fileName.substring(fileName.lastIndexOf("#")+1); // 封裝 fileNames.put(fileName, shortName); } } // 3. 保存到request域 request.setAttribute("fileNames", fileNames); // 4. 轉發 request.getRequestDispatcher("/downlist.jsp").forward(request, response);
在另外一個jsp中 顯示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>下載列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<table border="1" align="center">
<tr>
<th>序號</th>
<th>文件名</th>
<th>操作</th>
</tr>
<c:forEach var="en" items="${requestScope.fileNames}" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${en.value }</td>
<td>
<%--<a href="${pageContext.request.contextPath }/fileServlet?method=down&..">下載</a>--%>
<!-- 構建一個地址 -->
<c:url var="url" value="fileServlet">
<c:param name="method" value="down"></c:param>
<c:param name="fileName" value="${en.key}"></c:param>
</c:url>
<!-- 使用上面地址 -->
<a href="${url }">下載</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
點擊下載后,跳到下載方法中
/** * 3. 處理下載 */ private void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取用戶下載的文件名稱(url地址后追加數據,get) String fileName = request.getParameter("fileName");
//GET方式獲得的漢字需要轉碼 fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); // 先獲取上傳目錄路徑 //String basePath = getServletContext().getRealPath("/upload"); String basePath = "e:\\upload"; // 獲取一個文件流 InputStream in = new FileInputStream(new File(basePath,fileName)); // 如果文件名是中文,需要進行url編碼 fileName = URLEncoder.encode(fileName, "UTF-8"); // 設置下載的響應頭 response.setHeader("content-disposition", "attachment;fileName=" + fileName); // 獲取response字節流 OutputStream out = response.getOutputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = in.read(b)) != -1){ out.write(b, 0, len); } // 關閉 out.close(); in.close(); }
至此,下載完成,注意中文情況下,下載需要進行編碼