關於JSP中的文件上傳和下載操作 先分析一下上傳文件的流程 1-先通過前段頁面中的選擇文件選擇要上傳的圖片index.jsp 2-點擊提交按鈕,通過ajax的文件上傳訪問伺服器端 common.js 3-伺服器端響應保存或者下載保存上傳文件的FileUpload.java 下載文件的FileDown ...
關於JSP中的文件上傳和下載操作
先分析一下上傳文件的流程
1-先通過前段頁面中的選擇文件選擇要上傳的圖片
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <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" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/common.js"></script> <script type="text/javascript" src="js/ajaxfileupload.js"></script> </head> <body> <input type="file" value="上傳" name="inputImage" id="inputImage"> <input type="button" value="上傳" id="upload"> <a id="downLoad">下載</a> </body> </html>
2-點擊提交按鈕,通過ajax的文件上傳訪問伺服器端
common.js
var path = (function() { //獲取當前網址 var curWwwPath = window.document.location.href; //獲取主機地址之後的目錄 var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); //獲取主機地址 var localhostPath = curWwwPath.substring(0, pos); //獲取帶"/"的項目名 var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); return { curWwwPath: curWwwPath, pathName: pathName, localhostPath: localhostPath, projectName: projectName, //部署路徑 deployPath: localhostPath + projectName }; })();
// 文件下載 $("a[id=downLoad]").click(function(){ window.location.href=path.deployPath+"/fileDown"; }); // 文件上傳 $("input[id=upload]").click(function() { $.ajaxFileUpload( { url : path.deployPath + "/fileUp", // 處理頁面的絕對路徑 fileElementId : "inputImage", //file空間的id屬性 dataType : "json", success : function(data) { alert("上傳成功"); } }); });
3-伺服器端響應保存或者下載
保存上傳文件的FileUpload.java
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; 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 com.stu.util.HttpUtil; /** * 文件名稱: com.stu.fileupload.FileUpload.java<br/> * 初始作者: Administrator<br/> * 創建日期: 2018-1-31<br/> * 功能說明: 文件上傳 <br/> * =================================================<br/> * 修改記錄:<br/> * 修改作者 日期 修改內容<br/> * ================================================<br/> * Copyright (c) 2010-2011 .All rights reserved.<br/> */ public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // 獲取到當前伺服器所在的路徑 String serverPath = req.getSession().getServletContext().getRealPath("/"); // 設置保存上傳文件的路徑 String saveDirPath = serverPath + "img"; File saveDirPathFileObj = new File(saveDirPath); // 如果當用來存放文件的目錄不存在時,要創建該目錄 if (!saveDirPathFileObj.exists()) { saveDirPathFileObj.mkdirs(); } // 創建一個解析器工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設置工廠的緩存區大小 factory.setSizeThreshold(5 * 1024); // 文件上傳的解析器(文件上傳對象) ServletFileUpload upload = new ServletFileUpload(factory); // 設置上傳文件的最大值 upload.setSizeMax(3 * 1024 * 1024); // 設置編碼格式 upload.setHeaderEncoding("UTF-8"); try { // 上傳以後的文件名 List<String> uploadFileNames = new ArrayList<String>(); List<FileItem> fileItems = upload.parseRequest(req); System.out.println(fileItems); for (FileItem file : fileItems) { // 新的文件名 String saveFileName = UUID.randomUUID().toString().replace("-", ""); // 文件的尾碼 String oldFileName = new String(file.getName().getBytes(), "UTF-8"); System.out.println("oldFileName" + oldFileName); String fileType = oldFileName.substring(oldFileName.lastIndexOf(".")); // 新的文件路徑 String saveFilePath = saveDirPath + File.separator + saveFileName + fileType; uploadFileNames.add(saveFileName + fileType); // 保存上傳的文件 file.write(new File(saveFilePath)); } System.out.println(uploadFileNames); HttpUtil.setAttribute(req, "urls", uploadFileNames); res.setContentType("application/json;charset=utf-8"); PrintWriter pw = res.getWriter(); pw.print(JSONArray.fromObject(uploadFileNames)); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
下載文件的FileDownload.java
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; 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 com.stu.util.HttpUtil; /** * 文件名稱: com.stu.fileupload.FileUpload.java<br/> * 初始作者: Administrator<br/> * 創建日期: 2018-1-31<br/> * 功能說明: 文件上傳 <br/> * =================================================<br/> * 修改記錄:<br/> * 修改作者 日期 修改內容<br/> * ================================================<br/> * Copyright (c) 2010-2011 .All rights reserved.<br/> */ public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // 獲取到當前伺服器所在的路徑 String serverPath = req.getSession().getServletContext().getRealPath("/"); // 設置保存上傳文件的路徑 String saveDirPath = serverPath + "img"; File saveDirPathFileObj = new File(saveDirPath); // 如果當用來存放文件的目錄不存在時,要創建該目錄 if (!saveDirPathFileObj.exists()) { saveDirPathFileObj.mkdirs(); } // 創建一個解析器工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設置工廠的緩存區大小 factory.setSizeThreshold(5 * 1024); // 文件上傳的解析器(文件上傳對象) ServletFileUpload upload = new ServletFileUpload(factory); // 設置上傳文件的最大值 upload.setSizeMax(3 * 1024 * 1024); // 設置編碼格式 upload.setHeaderEncoding("UTF-8"); try { // 上傳以後的文件名 List<String> uploadFileNames = new ArrayList<String>(); List<FileItem> fileItems = upload.parseRequest(req); System.out.println(fileItems); for (FileItem file : fileItems) { // 新的文件名 String saveFileName = UUID.randomUUID().toString().replace("-", ""); // 文件的尾碼 String oldFileName = new String(file.getName().getBytes(), "UTF-8"); System.out.println("oldFileName" + oldFileName); String fileType = oldFileName.substring(oldFileName.lastIndexOf(".")); // 新的文件路徑 String saveFilePath = saveDirPath + File.separator + saveFileName + fileType; uploadFileNames.add(saveFileName + fileType); // 保存上傳的文件 file.write(new File(saveFilePath)); } System.out.println(uploadFileNames); HttpUtil.setAttribute(req, "urls", uploadFileNames); res.setContentType("application/json;charset=utf-8"); PrintWriter pw = res.getWriter(); pw.print(JSONArray.fromObject(uploadFileNames)); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
這裡面用到了一個HttpUtil類,代碼如下:
import javax.servlet.FilterConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * 文件名稱_com.niit.model2.util.Httputil.java</br> * 初始作逯ܿAdministrator</br> * 創建日期_2018-1-23</br> * 功能說明_這裡用一句話描述這個類的作用--此句話需刪除 <br/> * =================================================<br/> * 修改記錄_br/> * 修改作迠日期 修改內容<br/> * ================================================<br/> * Copyright (c) 2010-2011 .All rights reserved.<br/> */ public class HttpUtil { private HttpUtil() { } /** * 方法描述: [用於向不同的作用域存放屬性]</br> * 初始作迺 Administrator<br/> * 創建日期: 2018-1-23-上午11:24:45<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改記錄_br/> * 修改作迠日期 修改內容<br/> * ================================================<br/> * void */ public static void setAttribute(Object scopeObj, String name, Object value) { if (scopeObj instanceof HttpServletRequest) { ((HttpServletRequest) scopeObj).setAttribute(name, value); } if (scopeObj instanceof HttpSession) { ((HttpSession) scopeObj).setAttribute(name, value); } if (scopeObj instanceof ServletContext) { ((ServletContext) scopeObj).setAttribute(name, value); } } /** * 方法描述: [獲取作用域中指定名稱的屬性思</br> * 初始作迺 Administrator<br/> * 創建日期: 2018-1-23-上午11:29:17<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改記錄_br/> * 修改作迠日期 修改內容<br/> * ================================================<br/> * * @param scopeObj * @param name * @return * Object */ public static Object getAttribute(Object scopeObj, String name) { if (scopeObj instanceof HttpServletRequest) { return ((HttpServletRequest) scopeObj).getAttribute(name); } if (scopeObj instanceof HttpSession) { return ((HttpSession) scopeObj).getAttribute(name); } if (scopeObj instanceof ServletContext) { return ((ServletContext) scopeObj).getAttribute(name); } return null; } /** * 方法描述: [獲取上下文對象的方法]</br> * 初始作迺 Administrator<br/> * 創建日期: 2018-1-23-上午11:31:26<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改記錄_br/> * 修改作迠日期 修改內容<br/> * ================================================<br/> * * @return * ServletContext */ public static ServletContext getServletContext(Object sourceObj) { if (sourceObj instanceof HttpServletRequest) { return ((HttpServletRequest) sourceObj).getSession().getServletContext(); } if (sourceObj instanceof ServletConfig) { return ((ServletConfig) sourceObj).getServletContext(); } if (sourceObj instanceof FilterConfig) { return ((FilterConfig) sourceObj).getServletContext(); } return null; } /** * 方法描述: [獲取項目的實際路徑]</br> * 初始作迺 Administrator<br/> * 創建日期: 2018-1-23-上午11:45:47<br/> * 弿Nj版本: 2.0.0<br/> * =================================================<br/> * 修改記錄_br/> * 修改作迠日期 修改內容<br/> * ================================================<br/> * * @param req * @return * String */ public static String getContextPath(HttpServletRequest req) { return req.getContextPath(); } }
當然,代碼編輯好了也不要忘了在 WebRoot/WEB-INF/web.xml 中添加新建的Servlet,就是剛剛的兩個Java文件啦
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 文件上傳 --> <servlet> <servlet-name>fileUpload</servlet-name> <servlet-class>com.stu.fileupload.FileUpload</servlet-class> </servlet> <servlet-mapping> <servlet-name>fileUpload</servlet-name> <url-pattern>/fileUp</url-pattern> </servlet-mapping> <!-- 文件下載 --> <servlet> <servlet-name>fileDownload</servlet-name> <servlet-class>com.stu.fileupload.FileDownload</servlet-class> </servlet> <servlet-mapping> <servlet-name>fileDownload</servlet-name> <url-pattern>/fileDown</url-pattern> </servlet-mapping> </web-app>
這樣的話就可以運行啦。
TIP: 不要忘記相關的jar包和 js 包哦
在 WebRoot / WEB-INF / lib 下,有 commons-fileupload.jar 和 commons-io.jar ,另外 json-lib-x.x.x-jdkxx.jar 包是用來把上傳的返回數據修改為JSON格式的
在 WebRoot / js 下,導入 jquery.js , common.js , ajaxfileupload.js