Example of uploading and downloading files in JSP

Source: Internet
Author: User
Tags temporary file storage

Example of uploading and downloading files in JSP
I. Principles of File Upload
1. Prerequisites for file upload:
A. The method of form must be post.
B. The enctype of form must be multipart/form-data (determines the POST Request Method and the data Type of the Request body)
Note: When the form's enctype is multipart/form-data, the traditional method for obtaining request parameters is invalid.

Request body: (the MIME protocol is described and the body is composed of multiple parts)
----------------------------- 7dd32c39803b2
Content-Disposition: form-data; name = "username"

Wzhting
----------------------------- 7dd32c39803b2
Content-Disposition: form-data; name = "f1"; filename = "C: \ Documents ents and Settings \ wzhting \ Documents Processing \ a.txt"
Content-Type: text/plain

Aaaaaaaaaaaaaaaaaa
----------------------------- 7dd32c39803b2
Content-Disposition: form-data; name = "f2"; filename = "C: \ Documents ents and Settings \ wzhting \ Program transaction \ B .txt"
Content-Type: text/plain

Bbbbbbbbbbbbbbbbbbbbbbb
----------------------------- 7dd32c39803b2 --


C. The input type provided in form is a file-type file upload field.

Ii. Use third-party components to upload files
1. commons-fileupload component:
Jar: commons-fileupload.jar commons-io.jar
2. Core classes or interfaces
DiskFileItemFactory: sets the environment
Public void setSizeThreshold (int? SizeThreshold): sets the buffer size. The default value is 10 KB.
When the size of the uploaded file exceeds the buffer size, the fileupload component uses the Temporary File Cache to upload the file.
Public void setRepository (java. io. File repository): sets the directory for storing temporary files. The default is the system's temporary file storage directory.

ServletFileUpload: Core upload class (main function: parse the Request body content)
Boolean isMultipartContent (HttpServletRequest? Request): determines whether the enctype of a user's form is of the multipart/form-data type.
List parseRequest (HttpServletRequest request): resolves the content in the request body
SetFileSizeMax (4*1024*1024); // you can specify the size of a single uploaded file.
Upload. setSizeMax (6*1024*1024); // you can specify the total file size.
FileItem: indicates an input field in the form.
Boolean isFormField (): whether it is a common field
String getFieldName: obtains the field name of a common field.
String getString (): obtains the value of a common field.

InputStream getInputStream (): gets the input stream of the upload field
String getName (): Get the uploaded file name

3. Nine notes for File Upload
1. How to Ensure server security
Put the directory that saves the upload file into the WEB-INF directory.
2. Chinese garbled characters
2.1 Chinese Request Parameters for common fields
String value = FileItem. getString ("UTF-8 ");
2.2 The uploaded file name is in Chinese
Solution: request. setCharacterEncoding ("UTF-8 ");
3. Duplicate File Overwriting
System. currentMillions () + "_" cmda.txt (optimistic)

UUID + "_" a.txt: ensure that the file name is unique
4. Store uploaded files in different directories
Method 1: Create a folder on the current date and put all uploaded files in this folder.
Method 2: Use the hash code of the file name to break down the directory for storage.
Int hashCode = fileName. hashCode ();

1001 1010 1101 0010 1101 1100 1101
HashCode & 0xf; 0000 0000 0000 0000 0000 0000 0000 &
---------------------------------------------
0000 0000 0000 0000 0000 0000 0000 1010 obtain the last four digits of hashCode
0000 ~ 1111: integer 0 ~ 16 in total

1001 1010 1101 0010 1101 1100 1101
(HashCode & 0xf0) 0000 0000 0000 0000 0000 0000 1111 &
--------------------------------------------
0000 0000 0000 0000 0000 0000 1101 0000> 4
--------------------------------------------
0000 0000 0000 0000 0000 0000 0000
0000 ~ 1111: integer 0 ~ 16 in total
5. restrict the types of files uploaded by users
It is not advisable to determine the file extension.
It is reliable to determine its Mime type. FileItem. getContentType ();
6. How to restrict the size of files uploaded by users
6.1 single file size limit. The size is exceeded.
When an exception is caught, the following error occurs: org. apache. commons. fileupload. FileUploadBase. FileSizeLimitExceededException.
6.2 total file size limit. The size is exceeded.
When an exception is caught, the following error occurs: org. apache. commons. fileupload. FileUploadBase. SizeLimitExceededException.
7. Temporary File Problems
The commons-fileupload component does not delete temporary files that exceed the cache.

The FileItem. delete () method deletes temporary files. However, you must disable the stream.
8. NO content is uploaded when multiple files are uploaded.
If (fileName = null | "". equals (fileName. trim ())){
Continue;
}
9. Upload progress Detection
Register a progress listener for ServletFileUpload and pass the upload progress to the page for display.
// PBytesRead: the number of bytes currently read
// PContentLength: the object Length
// PItems: number of items
Public void update (long pBytesRead, long pContentLength,
Int pItems ){
System. out. println ("read:" + pBytesRead + ", file size:" + pContentLength + ", item:" + pItems );

}

Iv. File Upload example:

JSP code:

Servlet background code: 

Public class UploadServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); PrintWriter pout = response. getWriter (); try {// get the real path String storePath = getServletContext () for storing the uploaded file (). getRealPath ("/WEB-INF/files"); // sets the DiskFileItemFa Environment Ctory factory = new DiskFileItemFactory (); factory. setRepository (new File (getServletContext (). getRealPath ("/temp"); // sets the temporary storage directory. // determines whether the form is enctype = multipart/form-data type boolean isMultipart = ServletFileUpload. isMultipartContent (request); if (! IsMultipart) {System. out. println ("silly bird"); return;} // ServletFileUpload core class ServletFileUpload upload = new ServletFileUpload (factory); // upload. setProgressListener (new ProgressListener () {/// pBytesRead: the number of bytes read at present /// pContentLength: the length of the file /// pItems: items // public void update (long pBytesRead, long pContentLength, // int pItems) {// System. out. println ("read:" + pBytesRead + ", file size:" + pContentLength + ", item:" + pItems );//}////}); upload. setFileSizeMax (4*1024*1024); // you can specify the size of an uploaded file. setSizeMax (6*1024*1024); // set the total file size // parse List
 
  
Items = upload. parseRequest (request); for (FileItem item: items) {if (item. isFormField () {// common field String fieldName = item. getFieldName (); String fieldValue = item. getString ("UTF-8"); System. out. println (fieldName + "=" + fieldValue);} else {// obtain the MIME type String mimeType = item. getContentType (); // only images that can be uploaded if (mimeType. startsWith ("image") {// upload field InputStream in = item. getInputStream (); // the uploaded file name String fileNa Me = item. getName (); // C: \ Documents andif (fileName = null | "". equals (fileName. trim () {continue;} // Settings \ wzhting \ has been uploaded \ a.txt // a.txt fileName = fileName. substring (fileName. lastIndexOf ("\") + 1); // a.txt fileName = UUID. randomUUID () + "_" + fileName; System. out. println (request. getRemoteAddr () + "==================" + fileName ); // construct the output stream // decompress the storage directory String newStorePath = makeStorePath (storePath, fileName); // Based on // /WEB-INF/files and file name, create a new storage path // WEB-INF/files/1/12 String storeFile = newStorePath + "\" + fileName; // WEB-INF/files/1/2/sldfdslf.txt OutputStream out = new FileOutputStream (storeFile); byte B [] = new byte [1024]; int len =-1; while (len = in. read (B ))! =-1) {out. write (B, 0, len);} out. close (); in. close (); item. delete (); // delete temporary file }}} catch (org. apache. commons. fileupload. fileUploadBase. fileSizeLimitExceededException e) {// abnormal pout where a single file exceeds the size of the hour. write ("the size of a single file cannot exceed 4 MB");} catch (org. apache. commons. fileupload. fileUploadBase. sizeLimitExceededException e) {// abnormal pout when the total file size exceeds the threshold. write ("the total file size cannot exceed 6 MB");} catch (Exception e) {e. printStackTrace () ;}/// depending on/WEB-INF/files and text File Name, create a new storage path/WEB-INF/files/1/12 private String makeStorePath (String storePath, String fileName) {int hashCode = fileName. hashCode (); int dir1 = hashCode & 0xf; // 0000 ~ 1111: integer 0 ~ A total of 16 int dir2 = (hashCode & 0xf0)> 4; // 0000 ~ 1111: integer 0 ~ A total of 16 String path = storePath + "\" + dir1 + "\" + dir2; // WEB-INF/files/1/12 File file = new File (path ); if (! File. exists () file. mkdirs (); return path;} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
 


Zookeeper ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

V. File Download

1. display all the photo information stored above:

// Display all uploaded files, encapsulated in the domain object, and handed to jsp to display public class ShowAllFilesServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Map
 
  
Map = new HashMap
  
   
(); // Key: UUID file name; value: old file name // obtain the root directory of the stored file String storePath = getServletContext (). getRealPath ("/WEB-INF/files"); // recursively traverse the File file File = new file (storePath); treeWalk (File, map); // submit it to JSP for display: how to encapsulate data. it is encapsulated by Map. Key: UUID file name; value: old file name request. setAttribute ("map", map); request. getRequestDispatcher ("/listFiles. jsp "). forward (request, response);} // traverse/WEB-INF/files all files, put the File name in map private void treeWalk (file File, Map
   
    
Map) {if (file. isFile () {// is the file String uuidName = file. getName (); // UUID_a_a.txt // the actual file name String oldName = uuidName. substring (uuidName. indexOf ("_") + 1); map. put (uuidName, oldName);} else {// is a directory File [] fs = file. listFiles (); for (File f: fs) {treeWalk (f, map) ;}} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
   
  
 
2. display the content on the listFiles. jsp page of all files:
This site has the following good pictures
     
      
       
  Download $ {me. value}
  
3. Download DownloadServlet:

Public class DownloadServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html; charset = UTF-8"); OutputStream out = response. getOutputStream (); String filename = request. getParameter ("filename"); // get Request Method filename = new String (filename. getBytes ("ISO-8859-1"), "UTF-8"); // Chinese encoding // tri old file name Ng oldFileName = filename. split ("_") [1]; // obtain the storage path String storePath = getServletContext (). getRealPath ("/WEB-INF/files"); // obtain the full path of the file String filePath = makeStorePath (storePath, filename) + "\" + filename; // determine whether a File exists. file = new File (filePath); if (! File. exists () {out. write! The file you want to download may no longer exist ". getBytes ("UTF-8"); return;} InputStream in = new FileInputStream (file); // notifies the client to open response as a download. setHeader ("Content-Disposition", "attachment; filename =" + URLEncoder. encode (oldFileName, "UTF-8"); byte [] B = new byte [1024]; int len =-1; while (len = in. read (B ))! =-1) {out. write (B, 0, len);} in. close (); out. write ("Download successful ". getBytes ("UTF-8");} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response);} private String makeStorePath (String storePath, string fileName) {int hashCode = fileName. hashCode (); int dir1 = hashCode & 0xf; // 0000 ~ 1111: integer 0 ~ A total of 16 int dir2 = (hashCode & 0xf0)> 4; // 0000 ~ 1111: integer 0 ~ A total of 16 String path = storePath + "\" + dir1 + "\" + dir2; // WEB-INF/files/1/12 File file = new File (path ); if (! File. exists () file. mkdirs (); return path ;}}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.