File Upload,

Source: Internet
Author: User

File Upload,
I. File Upload Overview 1. The function of File Upload is network hard disk! Is used to upload and download files. Fill in a complete resume on the recruitment website and upload photos. 2. There are many requirements for file uploading on the page. Note the following:

  • A form must be used instead of a hyperlink;
  • The form method must be POST, not GET;
  • The form's enctype must be multipart/form-data;
  • Add a file form field to the form, that is, <input type = "file" name = "xxx"/>
1 <form action = "$ {pageContext. request. contextPath}/FileUploadServlet "method =" post "enctype =" multipart/form-data "> 2 User Name: <input type = "text" name = "username"/> <br/> 3. File 1: <input type = "file" name = "file1"/> <br/> 4 file 2: <input type = "file" name = "file2"/> <br/> 5 <input type = "submit" value = "submit"/> 6 </form>
3. Servlet requirements for file uploading
  • The request. getParameter (String) method obtains the character content of the specified form field, but the file upload form is not a character content, but a byte content, so it is invalid.
  • ServletInputStream request. getInputStream (): contains the entire request body.

4. multipart form body

① Multiple parts are generated at intervals, that is, a form item is a part.

② A part contains the request header, blank rows, and request body.

③ Common form items:

  • 1 Head: Content-Disposition: contains name = "xxxx", that is, the form Item name
  • Body is the value of the form item.

④ File form items:

  • Content-Disposition: contains name = "xx", that is, the form item name, and a filename = "xx", indicating the name of the uploaded file
  • Content-Type: The MINE Type of the uploaded file, for example, image/pjpeg, which indicates the uploaded image and the image with the jpg extension in the figure.
  • Body is the content of the uploaded file
Request Headersview parsedPOST /form1.jsp HTTP/1.1Host: localhost:8080Connection: keep-aliveContent-Length: 479756Cache-Control: max-age=0Origin: http://localhost:8080Upgrade-Insecure-Requests: 1Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8Wne2EqQO2Ps7E8mUser-Agent: ****Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Referer: http://localhost:8080/form1.jspAccept-Encoding: gzip, deflate, brAccept-Language: zh,en-US;q=0.8,en;q=0.6,zh-CN;q=0.4Cookie: Idea-e96526d7=db12919d-58f1-479a-b0f7-3104911c767b; JSESSIONID=9DEFDF98FE8715CB5707772F874D8C82Request Payload------WebKitFormBoundary8Wne2EqQO2Ps7E8mContent-Disposition: form-data; name="username"zhangsan------WebKitFormBoundary8Wne2EqQO2Ps7E8mContent-Disposition: form-data; name="picture"; filename="2.jpg"Content-Type: image/jpeg------WebKitFormBoundary8Wne2EqQO2Ps7E8m--
5 commons-fileupload is an upload component provided by the apache commons component. Its main task is to help us parse request. getInputStream (). The following JAR packages are required for the fileupload component:
  • Commons-fileupload.jar, core package;
  • Commons-io.jar, dependent package.

Ii. Simple fileupload Application

1. The core classes of fileupload include DiskFileItemFactory, ServletFileUpload, and FileItem. To use the fileupload component, follow these steps:

① Create a factory class DiskFileItemFactory object: DiskFileItemFactory factory = new DiskFileItemFactory ()

② Use the factory to create a parser object: ServletFileUpload fileUpload = new ServletFileUpload (factory)

③ Use the parser to parse the request object: List <FileItem> list = fileUpload. parseRequest (request)

2. FileItem

A FileItem object corresponds to a form item (form field ). A form contains file fields and common fields. You can use the isFormField () method of the FileItem class to determine whether a form field is a common field. If it is not a common field, it is a file field.
  • Boolean isFormField (): determines whether the current form field is a common text field. If false is returned, it indicates a file field;
  • String getFieldName (): obtains the field name. For example, <input type = "text" name = "username"/>. username is returned;
  • String getName (): Get the file name of the file field;
  • String getString (String charset): obtains the content of a field. If it is a file field, it obtains the file content. Of course, the uploaded file must be a text file;
  • String getContentType (): gets the type of the uploaded file, for example, text/plain.
  • Long getSize (): returns the number of bytes of the uploaded file;
  • InputStream getInputStream (): gets the input stream corresponding to the uploaded file;
  • Void write (File): saves the uploaded File to the specified File.

3. Example:

1 package servlet; 2 3 import org. apache. commons. fileupload. fileItem; 4 import org. apache. commons. fileupload. fileUploadException; 5 import org. apache. commons. fileupload. disk. diskFileItemFactory; 6 import org. apache. commons. fileupload. servlet. servletFileUpload; 7 8 import javax. servlet. servletException; 9 import javax. servlet. annotation. webServlet; 10 import javax. servlet. http. httpServlet; 11 import javax. servlet. http. httpServletRequest; 12 import javax. servlet. http. httpServletResponse; 13 import java. io. file; 14 import java. io. IOException; 15 import java. util. list; 16 17 @ WebServlet (name = "Upload2Servlet", urlPatterns = "/Upload2Servlet") 18 public class Upload2Servlet extends HttpServlet {19 protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {20 request. setCharacterEncoding ("UTF-8"); 21 response. setContentType ("text/html; charset = UTF-8"); 22/* 23*1. Get factory 24*2. Create parser 25*3. parse request, obtain the FileItem set 26*4. traverse the FileItem set and call its API to save the file 27 */28 DiskFileItemFactory factory = new DiskFileItemFactory (); 29 ServletFileUpload sfu = new ServletFileUpload (factory); 30 try {31 List <FileItem> fileItems = sfu. parseRequest (request); 32 FileItem fileItem1 = fileItems. get (0); 33 FileItem fileItem2 = fileItems. get (1); 34 35 System. out. println ("Normal Form item Demonstration:" + fileItem1.get () + 36 "=" + fileItem1.toString (); 37 System. out. println ("file form Demo:"); 38 System. out. println ("Content-Type:" + fileItem2.getContentType (); 39 System. out. println ("size:" + fileItem2.getSize (); 40 System. out. println ("filename:" + fileItem2.getName (); 41 // save the File 42 File destFile = new File ("/Users/Shared/picture.jpg "); 43 try {44 fileItem2.write (destFile); 45} catch (Exception e) {46 throw new RuntimeException (e); 47} 48} catch (FileUploadException e) {49 throw new RuntimeException (e); 50} 51} 52}
1 <% @ page contentType = "text/html; charset = UTF-8 "language =" java "%> 2 <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> 3 

Iii. upload details

1. The file must be saved to the WEB-INF!
* The purpose is not to allow direct access from the browser!
* Save the file to the WEB-INF directory!
2. File name problems
* Some browsers upload absolute paths for file names, which requires cutting! C: \ files \ baibing.jpg
String filename = fi2.getName ();
Int index = filename. lastIndexOf ("\\");
If (index! =-1 ){
Filename = filename. substring (index + 1 );
}
* The file name is garbled or the common form item is garbled: request. setCharacterEncoding ("UTF-8"); Because fileupload internally calls request. getCharacterEncoding ();
> Request. setCharacterEncoding ("UTF-8"); // low priority
> ServletFileUpload. setHeaderEncoding ("UTF-8"); // high priority
* File name: we need to add a name prefix for each file, which must be unique. Uuid
> Filename = CommonUtils. uuid () + "_" + filename;
3. Directory cracking
* You cannot store as many files in a directory.
> Break down the first character: Use the first letter of the file as the directory name, for example, abc.txt. Then, save the file to directory. If directory a does not exist, create it.
> Time discretization: use the current date as the directory.
> Hash hash:
* Get the int value through the file name, that is, call hashCode ()
* The int value is converted to hexadecimal 0 ~ 9, ~ F
* Obtain the first two digits of hexadecimal format to generate a directory. The directory is a layer 2 directory! For example: 1B2C3D4E5F,/1/B/save the file.
4. Size Limit of uploaded files
* Single file size limit
> Sfu. setFileSizeMax (100*1024): limits the size of a single file to kb.
> The preceding method must be called before resolution starts!
> If the file to be uploaded exceeds the limit, an exception is thrown when the parseRequest () method is executed! FileUploadBase. FileSizeLimitExceededException
* All data size restrictions for the entire request
> Sfu. setSizeMax (1024*1024); // the size of the entire form is limited to 1 MB.
> This method must be called before the parseRequest () method.
> If the file to be uploaded exceeds the limit, an exception is thrown when the parseRequest () method is executed! FileUploadBase. SizeLimitExceededException
5. cache size and temporary directory
* Cache size: how large the cache size is before it is saved to the hard disk! The default value is 10KB.
* Temporary directory: directory to which the disk is saved
Set cache size and temporary directory: new DiskFileItemFactory (20*1024, new File ("F:/temp "))
 

Iv. Examples of directory discretization, upload size restrictions, cache size, and temporary directory:

1 package servlet; 2 3 import cn. itcast. commons. commonUtils; 4 import org. apache. commons. fileupload. fileItem; 5 import org. apache. commons. fileupload. fileUploadBase; 6 import org. apache. commons. fileupload. fileUploadException; 7 import org. apache. commons. fileupload. disk. diskFileItemFactory; 8 import org. apache. commons. fileupload. servlet. servletFileUpload; 9 10 import javax. servlet. servletException; 11 Import javax. servlet. annotation. webServlet; 12 import javax. servlet. http. httpServlet; 13 import javax. servlet. http. httpServletRequest; 14 import javax. servlet. http. httpServletResponse; 15 import java. io. file; 16 import java. io. IOException; 17 import java. util. list; 18 @ WebServlet (name = "Upload3Servlet", urlPatterns = "/Upload3Servlet") 19 public class Upload3Servlet extends HttpServlet {20 protected void DoPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {21 request. setCharacterEncoding ("UTF-8"); 22 response. setContentType ("text/html; charset = UTF-8"); 23 24 // factory 25 DiskFileItemFactory factory = new DiskFileItemFactory (20*1024, new File ("/Users/Shared/temp"); 26 // parser 27 ServletFileUpload sfu = new ServletFileUpload (factory); 28 29 // sfu. setFileSizeMax (100*1024); // limit the size of a single file to kb30 // sfu. setSizeMax (100*1024); // limit the size of the entire form to kb31 // parse the statement to obtain List32 try {33 List <FileItem> list = sfu. parseRequest (request); 34 FileItem fi = list. get (1); 35 36 // 1. Obtain the file storage path 37 String root = this. getServletContext (). getRealPath ("/WEB-INF/files "); 38/* 39*2. Generate a L2 directory 40 * get the file name 41 * Get hashCode42 * Forward to hexadecimal 43 * Get the first two characters to generate the directory 44 **/45 String filename = fi. getName (); // get the name of the uploaded file 46 // process the file Problem 47 int index = filename. lastIndexOf ("//"); 48 if (index! = 1) {49 filename = filename. substring (index + 1); 50} 51 // Add a UUID prefix to the file name to handle the same name issue 52 String savename = CommonUtils. uuid () + "_" + filename; 53 // 1. Obtain hashCode54 int hCode = filename. hashCode (); 55 String hex = Integer. toHexString (hCode); 56 // 2. Obtain the first two letters of hex and connect them with the root to generate a complete path 57 File dirFile = new File (root, hex. charAt (0) + "/" + hex. charAt (1); 58 // 3. Create a directory chain 59 dirFile. mkdirs (); 60 // 4. Create a directory File 61 File destFile = new Fi Le (dirFile, savename); 62 // 5. Save 63 fi. write (destFile); 64} catch (FileUploadException e) {65 if (e instanceof FileUploadBase. fileSizeLimitExceededException) {66 request. setAttribute ("msg", "the file you uploaded exceeds kb! "); 67 request. getRequestDispatcher ("/form3.jsp "). forward (request, response); 68} 69} catch (Exception e) {70 e. printStackTrace (); 71} 72} 73}

 

 

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.