先分析一下上傳文件的流程
1-先通過(guò)前段頁(yè)面中的選擇文件選擇要上傳的圖片
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-點(diǎn)擊提交按鈕,通過(guò)ajax的文件上傳訪問(wèn)服務(wù)器端
common.js
var path = (function() { //獲取當(dāng)前網(wǎng)址 var curWwwPath = window.document.location.href; //獲取主機(jī)地址之后的目錄 var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); //獲取主機(jī)地址 var localhostPath = curWwwPath.substring(0, pos); //獲取帶"/"的項(xiàng)目名 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", // 處理頁(yè)面的絕對(duì)路徑 fileElementId : "inputImage", //file空間的id屬性 dataType : "json", success : function(data) { alert("上傳成功"); } }); });
3-服務(wù)器端響應(yīng)保存或者下載
保存上傳文件的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; /** * 文件名稱(chēng): com.stu.fileupload.FileUpload.javabr/> * 初始作者: Administratorbr/> * 創(chuàng)建日期: 2018-1-31br/> * 功能說(shuō)明: 文件上傳 br/> * =================================================br/> * 修改記錄:br/> * 修改作者 日期 修改內(nèi)容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 { // 獲取到當(dāng)前服務(wù)器所在的路徑 String serverPath = req.getSession().getServletContext().getRealPath("/"); // 設(shè)置保存上傳文件的路徑 String saveDirPath = serverPath + "img"; File saveDirPathFileObj = new File(saveDirPath); // 如果當(dāng)用來(lái)存放文件的目錄不存在時(shí),要?jiǎng)?chuàng)建該目錄 if (!saveDirPathFileObj.exists()) { saveDirPathFileObj.mkdirs(); } // 創(chuàng)建一個(gè)解析器工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設(shè)置工廠的緩存區(qū)大小 factory.setSizeThreshold(5 * 1024); // 文件上傳的解析器(文件上傳對(duì)象) ServletFileUpload upload = new ServletFileUpload(factory); // 設(shè)置上傳文件的最大值 upload.setSizeMax(3 * 1024 * 1024); // 設(shè)置編碼格式 upload.setHeaderEncoding("UTF-8"); try { // 上傳以后的文件名 ListString> uploadFileNames = new ArrayListString>(); ListFileItem> 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; /** * 文件名稱(chēng): com.stu.fileupload.FileUpload.javabr/> * 初始作者: Administratorbr/> * 創(chuàng)建日期: 2018-1-31br/> * 功能說(shuō)明: 文件上傳 br/> * =================================================br/> * 修改記錄:br/> * 修改作者 日期 修改內(nèi)容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 { // 獲取到當(dāng)前服務(wù)器所在的路徑 String serverPath = req.getSession().getServletContext().getRealPath("/"); // 設(shè)置保存上傳文件的路徑 String saveDirPath = serverPath + "img"; File saveDirPathFileObj = new File(saveDirPath); // 如果當(dāng)用來(lái)存放文件的目錄不存在時(shí),要?jiǎng)?chuàng)建該目錄 if (!saveDirPathFileObj.exists()) { saveDirPathFileObj.mkdirs(); } // 創(chuàng)建一個(gè)解析器工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設(shè)置工廠的緩存區(qū)大小 factory.setSizeThreshold(5 * 1024); // 文件上傳的解析器(文件上傳對(duì)象) ServletFileUpload upload = new ServletFileUpload(factory); // 設(shè)置上傳文件的最大值 upload.setSizeMax(3 * 1024 * 1024); // 設(shè)置編碼格式 upload.setHeaderEncoding("UTF-8"); try { // 上傳以后的文件名 ListString> uploadFileNames = new ArrayListString>(); ListFileItem> 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(); } } }
這里面用到了一個(gè)HttpUtil類(lèi),代碼如下:
import javax.servlet.FilterConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * 文件名稱(chēng)_com.niit.model2.util.Httputil.java/br> * 初始作逯ܿAdministrator/br> * 創(chuàng)建日期_2018-1-23/br> * 功能說(shuō)明_這里用一句話(huà)描述這個(gè)類(lèi)的作用--此句話(huà)需刪除 br/> * =================================================br/> * 修改記錄_br/> * 修改作迠日期 修改內(nèi)容br/> * ================================================br/> * Copyright (c) 2010-2011 .All rights reserved.br/> */ public class HttpUtil { private HttpUtil() { } /** * 方法描述: [用于向不同的作用域存放屬性]/br> * 初始作迺 Administratorbr/> * 創(chuàng)建日期: 2018-1-23-上午11:24:45br/> * 弿Nj版本: 2.0.0br/> * =================================================br/> * 修改記錄_br/> * 修改作迠日期 修改內(nèi)容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); } } /** * 方法描述: [獲取作用域中指定名稱(chēng)的屬性思/br> * 初始作迺 Administratorbr/> * 創(chuàng)建日期: 2018-1-23-上午11:29:17br/> * 弿Nj版本: 2.0.0br/> * =================================================br/> * 修改記錄_br/> * 修改作迠日期 修改內(nèi)容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; } /** * 方法描述: [獲取上下文對(duì)象的方法]/br> * 初始作迺 Administratorbr/> * 創(chuàng)建日期: 2018-1-23-上午11:31:26br/> * 弿Nj版本: 2.0.0br/> * =================================================br/> * 修改記錄_br/> * 修改作迠日期 修改內(nèi)容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; } /** * 方法描述: [獲取項(xiàng)目的實(shí)際路徑]/br> * 初始作迺 Administratorbr/> * 創(chuàng)建日期: 2018-1-23-上午11:45:47br/> * 弿Nj版本: 2.0.0br/> * =================================================br/> * 修改記錄_br/> * 修改作迠日期 修改內(nèi)容br/> * ================================================br/> * * @param req * @return * String */ public static String getContextPath(HttpServletRequest req) { return req.getContextPath(); } }
當(dāng)然,代碼編輯好了也不要忘了在 WebRoot/WEB-INF/web.xml 中添加新建的Servlet,就是剛剛的兩個(gè)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>
這樣的話(huà)就可以運(yùn)行啦。
TIP: 不要忘記相關(guān)的jar包和 js 包哦
在 WebRoot / WEB-INF / lib 下,有 commons-fileupload.jar 和 commons-io.jar ,另外 json-lib-x.x.x-jdkxx.jar 包是用來(lái)把上傳的返回?cái)?shù)據(jù)修改為JSON格式的
在 WebRoot / js 下,導(dǎo)入 jquery.js , common.js , ajaxfileupload.js
以上這篇JavaServlet的文件上傳和下載實(shí)現(xiàn)方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
標(biāo)簽:南京 內(nèi)江 大連 銅川 黃石 貸款邀約 樂(lè)山 廣州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《JavaServlet的文件上傳和下載實(shí)現(xiàn)方法》,本文關(guān)鍵詞 JavaServlet,的,文件,上傳,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。