How to upload and download assumervlet files,
First, analyze the process of uploading files.
1-select the image to be uploaded from the selected file on the previous page.
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">
2-click Submit to access the server through ajax File Upload
Common. js
Var path = (function () {// get the current URL var curWwwPath = too many Doc ument. location. href; // The directory after obtaining the host address var pathName = Invalid invalid Doc ument. location. pathname; var pos = curWwwPath. indexOf (pathName); // obtain the host address var localhostPath = curWwwPath. substring (0, pos); // obtain the project name with "/" var projectName = pathName. substring (0, pathName. substr (1 ). indexOf ('/') + 1); return {curWwwPath: curWwwPath, pathName: pathName, localhostPath: localhostPath, projectName: projectName, // deployment path deployPath: localhostPath + projectName };})();
// File downLoad $ ("a [id = downLoad]"). click (function () {window. location. href = path. deployPath + "/fileDown" ;}); // File upload $ ("input [id = upload]"). click (function () {$. ajaxFileUpload ({url: path. deployPath + "/fileUp", // processing the absolute path of the page fileElementId: "inputImage", // id attribute dataType of the file space: "json", success: function (data) {alert ("uploaded successfully ");}});});
3-Server Response save or download
Save the 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. apa Che. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; import com. stu. util. httpUtil;/*** file name: com. stu. fileupload. fileUpload. java <br/> * Author: Administrator <br/> * creation date: <br/> * function description: file Upload <br/> * ==================================== ======================< br/> * modify the record: <br/> * modify author date Content <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 {// obtain the path of the current Server String serverPath = req. getSession (). getServletC Ontext (). getRealPath ("/"); // set the path String saveDirPath = serverPath + "img"; File saveDirPathFileObj = new File (saveDirPath ); // if the directory used to store files does not exist, create this directory if (! SaveDirPathFileObj. exists () {saveDirPathFileObj. mkdirs ();} // create a parser factory DiskFileItemFactory factory = new DiskFileItemFactory (); // set the factory cache size factory. setSizeThreshold (5*1024); // The File upload Parser (File upload object) ServletFileUpload upload = new ServletFileUpload (factory); // you can specify the maximum upload value for an uploaded file. setSizeMax (3*1024*1024); // sets the encoding format upload. setHeaderEncoding ("UTF-8"); try {// List of uploaded file names <String> uploadFileNames = new ArrayList <String> (); List <FileItem> fileItems = upload. parseRequest (req); System. out. println (fileItems); for (FileItem file: fileItems) {// new file name String saveFileName = UUID. randomUUID (). toString (). replace ("-", ""); // file suffix String oldFileName = new String (file. getName (). getBytes (), "UTF-8"); System. out. println ("oldFileName" + oldFileName); String fileType = oldFileName. substring (oldFileName. lastIndexOf (". "); // the new File path String saveFilePath = saveDirPath + File. separator + saveFileName + fileType; uploadFileNames. add (saveFileName + fileType); // Save the uploaded 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. apa Che. commons. fileupload. fileUploadException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; import com. stu. util. httpUtil;/*** file name: com. stu. fileupload. fileUpload. java <br/> * Author: Administrator <br/> * creation date: <br/> * function description: file Upload <br/> * ==================================== ======================< br/> * modify the record: <br/> * modify author date Content <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 {// obtain the path of the current Server String serverPath = req. getSession (). getServletC Ontext (). getRealPath ("/"); // set the path String saveDirPath = serverPath + "img"; File saveDirPathFileObj = new File (saveDirPath ); // if the directory used to store files does not exist, create this directory if (! SaveDirPathFileObj. exists () {saveDirPathFileObj. mkdirs ();} // create a parser factory DiskFileItemFactory factory = new DiskFileItemFactory (); // set the factory cache size factory. setSizeThreshold (5*1024); // The File upload Parser (File upload object) ServletFileUpload upload = new ServletFileUpload (factory); // you can specify the maximum upload value for an uploaded file. setSizeMax (3*1024*1024); // sets the encoding format upload. setHeaderEncoding ("UTF-8"); try {// List of uploaded file names <String> uploadFileNames = new ArrayList <String> (); List <FileItem> fileItems = upload. parseRequest (req); System. out. println (fileItems); for (FileItem file: fileItems) {// new file name String saveFileName = UUID. randomUUID (). toString (). replace ("-", ""); // file suffix String oldFileName = new String (file. getName (). getBytes (), "UTF-8"); System. out. println ("oldFileName" + oldFileName); String fileType = oldFileName. substring (oldFileName. lastIndexOf (". "); // the new File path String saveFilePath = saveDirPath + File. separator + saveFileName + fileType; uploadFileNames. add (saveFileName + fileType); // Save the uploaded 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 ();}}}
The following code uses an HttpUtil class:
Import javax. servlet. filterConfig; import javax. servlet. servletConfig; import javax. servlet. servletContext; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpSession;/*** file name_com. niit. model2.util. httputil. java </br> * initial launch Administrator </br> * creation date _ </br> * function description _ here is a sentence to describe the role of this class-this sentence is required delete <br/> * ====================================== ====================< br/> * modify record _ br/> * as the modification date <br/> * = ========================================================== =====< br/> * Copyright (c) 2010-2011. all rights reserved. <br/> */public class HttpUtil {private HttpUtil () {}/ *** method description: [used to store attributes in different scopes] </br> * Initial operation as Administrator <br/> * creation date:-11:24:45 <br/> * release History version: 2.0.0 <br/> * ====================================== ====================< br/> * modify record _ br/> * as the modification date <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) ;}/ *** method description: [get the attributes of the specified name in the scope </br> * Initial operation as Administrator <br/> * creation date:-11:29:17 <br/> * release History version: 2.0.0 <br/> * ====================================== ====================< br/> * modify record _ br/> * as the modification date <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;}/*** method description: [How to obtain the context object] </br> * Initial Administrator <br/> * creation date:-11:31:26 <br/> * zookeeper version: 2.0.0 <br/> * ====================================== ====================< br/> * modify record _ br/> * as the modification date <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;}/*** method Description: [obtain the actual path of the project] </br> * Initial Administrator <br/> * creation date: -11:45:47 am <br/> * zookeeper version: 2.0.0 <br/> * ====================================== ====================< br/> * modify record _ br/> * as the modification date <br/> * = ========================================================== =====< br/> ** @ param req * @ return * String */public static String getContextPath (HttpServletRequest req) {return req. getContextPath ();}}
Of course, after the code is edited, do not forget to add the new Servlet in WebRoot/WEB-INF/web. xml, just two Java files.
<? 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> <! -- File Upload --> <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> <! -- File download --> <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>
In this way, you can run it.
TIP: Do not forget the relevant jar and js packages.
Under WebRoot/WEB-INF/lib, there are commons-fileupload.jar and commons-io.jar, And the json-lib-x.x.x-jdkxx.jar package is used to modify the uploaded response data to JSON format
Under WebRoot/js, import jquery. js, common. js, and ajaxfileupload. js
The method for uploading and downloading the assumervlet File above is all the content that I have shared with you. I hope to give you a reference and support for the help house.