JavaWeb中的檔案上傳和下載
阿新 • • 發佈:2019-01-01
對於檔案上傳,瀏覽器在上傳的過程中是將檔案以流的形式提交到伺服器端的,如果直接使用Servlet獲取上傳檔案的輸入流然後再解析裡面的請求引數是比較麻煩,所以一般選擇採用apache的開源工具common-fileupload這個檔案上傳元件。這個common-fileupload上傳元件的jar包可以去apache官網上面下載,也可以在struts的lib資料夾下面找到,struts上傳的功能就是基於這個實現的。common-fileupload是依賴於common-io這個包的,所以還需要下載這個包。
servlet控制器
package com.mipo.servlet; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; 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; import org.apache.tomcat.util.http.fileupload.IOUtils; public class CommonFileUploadController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if(null == method || "".equals(method)) { processUpload(request,response); }else if("listFiles".equals(method)) { processListFiles(request,response); }else if("download".equals(method)) { processDownload(request,response); } } /** * 下載檔案 * @param request * @param response */ private void processDownload(HttpServletRequest request, HttpServletResponse response) { //得到要下載的檔名 String filename = request.getParameter("filename"); //二進位制檔案資料 response.setContentType("application/octet-stream"); try { //處理下載檔案-中文檔名亂碼問題 response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"), "ISO8859-1")); //getRealPath(String path)為給定虛擬路徑返回包含實際路徑的 String。 //獲取檔案路徑 String filepath = this.getServletContext().getRealPath("/upload")+File.separator+filename; /*絕對路徑(D:\Eclipse\.meta data\. plugins\org.eclipse.wst.server.core\tmp0\wtpwebsaspps\JSP檔案上傳與下載\ u p load\圖表.docx)*/ System.out.println("filepath:"+filepath); //得到要下載的檔案 File file = new File(filepath); //讀取下載的檔案,儲存到輸入流中 InputStream is = new BufferedInputStream(new FileInputStream(file)); //建立輸出流 ServletOutputStream os = response.getOutputStream(); //Apache中Commons IO的jar包封裝好的複製方法,直接呼叫即可 IOUtils.copy(is, os); //重新整理輸出流 os.flush(); //關閉輸入輸出流 os.close(); is.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 顯示可下載檔案列表 * @param request * @param response */ private void processListFiles(HttpServletRequest request, HttpServletResponse response) { //獲取上傳檔案目錄下所有檔案 File file = new File(this.getServletContext().getRealPath("/upload")); //listFiles()返回一個抽象路徑名陣列,這些路徑名錶示此抽象路徑名錶示的目錄中的檔案。將此陣列儲存到request中 request.setAttribute("files", file.listFiles()); try { //轉發到file-download.jsp request.getRequestDispatcher("file-download.jsp?servletName="+request.getParameter("servletName")).forward(request, response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }; } /** * 上傳檔案 * @param request * @param response */ private void processUpload(HttpServletRequest request, HttpServletResponse response) { //為基於磁碟的檔案建立一個工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //建立一個檔案上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳檔名的中文亂碼 upload.setHeaderEncoding("UTF-8"); String value = null; try { //使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { //如果FileItem中封裝的是普通輸入項(普通元件)的資料 if(item.isFormField()) { //獲取HTML表單中元件的名字 String name = item.getFieldName(); if("servletName".equals(name)) { value = item.getString();//表單中元件的值 System.out.println(name+"="+value);//servletName=CommonFileUploadController } //如果FileItem中封裝的是上傳檔案 }else { String path = this.getServletContext().getRealPath("/upload") + File.separator + item.getName(); /*絕對路徑 D:\Eclipse\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\JSP檔案上傳與下載\ u p load\圖表.docx)*/ System.out.println("path:"+path); //將檔案寫入到指定檔案中 item.write(new File(path)); } } //重定向到servlet response.sendRedirect(request.getContextPath() + "/CommonFileUploadController?method=listFiles&servletName=" + value); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
index.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>首頁</title> </head> <body> <jsp:forward page="file-upload.jsp"> <jsp:param value="CommonFileUploadController" name="servletName"/> </jsp:forward> </body> </html>
file-upload.jsp
file-download.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>上傳檔案</title> </head> <body> <!-- method=“post”:檔案上傳必須使用post,因為使用get能夠傳送的資料大小有限制 enctype=“multipart/form-data”:表明當前表單提交的資料有多個部分組成 --> <form action="${pageContext.request.contextPath}/${param.servletName}" method="post" enctype="multipart/form-data"> <input type="text" name="servletName" value="${param.servletName }"> <input type="text" name="name" value="jobs"> <input type="file" name="file"> <button type="submit">Submit</button> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>下載檔案</title>
</head>
<body>
<ul>
<c:forEach items="${files }" var="file">
<li>
<a href="${pageContext.request.contextPath}/${param.servletName}?method=download&filename=${file.name}">${file.name}</a>
</li>
</c:forEach>
</ul>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>JSP檔案上傳與下載</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>CommonFileUploadController</servlet-name>
<servlet-class>com.mipo.servlet.CommonFileUploadController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CommonFileUploadController</servlet-name>
<url-pattern>/CommonFileUploadController</url-pattern>
</servlet-mapping>
</web-app>
執行結果