File Upload (java), file upload java

Source: Internet
Author: User

File Upload (java), file upload java

[1] Introduction
> Send a local client file to the server for saving.
> An uploaded file is sent to the server as a stream.

[2] form settings (forms are generally used for file uploads)

> When uploading a file to the server, the form must use the post request.
> Default form attribute enctype = "application/x-www-form-urlencoded"
-This attribute indicates that the content in the Request body will be URL encoded.
> The form enctype of the file to be uploaded must be set to multipart/form-data.
-Multipart/form-data indicates that a form is a multi-part form.
-If the type is set to it, each of our form items will be sent to the server as a separate component.
-Separate multiple parts using separators similar to ----------------------------- 7df2d08c0892
> When the form is set to multipart/form-data, request. getParameter () becomes invalid. We cannot obtain request parameters through this method.

1 <form action = "$ {pageContext. request. contextPath}/FileUploadServlet "method =" post "enctype =" multipart/form-data "> 2 users: <input type = "text" name = "name"> 3 <input type = "file" name = "photo"> <br> 4 <input type = "submit" value = "Submit"> 5 </form>

[3] FileUpload
> We generally use the commons-fileupload-1.3.1.jar tool to parse multipart requests.
> Fileupload depends on commons-io. Therefore, if Filtupload is used, the I/O package needs to be imported simultaneously.
> Core class:
DiskFileItemFactory
-Factory class, used to build a parser instance.

ServletFileUpload
-Parser class, which is used to parse request information in the request.

FileItem
-The tool encapsulates every part in our request as a FileItem object. To process file uploads, you only need to call the method of this object.
-Method:
Boolean isFormField () --> whether the current form item is a normal form item; true indicates a normal form item; false indicates a file form item.
String getContentType () --> the returned object type is the MIME value.
String getFieldName () --> get the name attribute value of the form item
String getName () --> get the name of the uploaded file
Long getSize () --> get the object size
String getString (String encoding) --> to obtain the value attribute value of a form item, an encoding is required as a parameter.
Void write (File file) --> write the content in the form item to the disk

> Steps:
1. Obtain the factory instance [DiskFileItemFactory]
2. Get the parser class instance [ServletFileUpload]
3. parse the request to obtain FileItem [parseRequest ()]

1 @ WebServlet ("/FileUploadServlet") 2 public class FileUploadServlet extends HttpServlet {3 private static final long serialVersionUID = 1L; 4 5 protected void doPost (HttpServletRequest request, response) throws ServletException, IOException {6 7 // create a factory class 8 DiskFileItemFactory factory = new DiskFileItemFactory (); 9 // create a FileUploadServlet object, use this object to complete the upload function 10 ServletFileUpload fileUpload = new ServletFileUpload (factory); 11 // use this fileUpload object to parse the request 12 try {13 List <FileItem> fileList = fileUpload. parseRequest (request); 14 for (FileItem item: fileList) {15 if (item. isFormField () {16 // represents the normal form item 17 String name = item. getFieldName (); 18 String value = item. getString ("UTF8"); 19 System. out. println (name + ":" + value); 20} else {21 // indicates the uploaded file 22 long size = item. getSize (); 23 String contentType = item. getContentType (); 24 String name = item. getName (); 25 String fieldName = item. getFieldName (); 26 System. out. println (size + ":" + contentType + ":" + name + ":" + fieldName); 27 String uuid = UUID. randomUUID (). toString (); // The name is repeated. The last chapter will overwrite the previous chapter 28 uuid. replace ("-", ""); 29 item. write (new File ("C: \ Users \ kanglu \ Desktop \" + uuid + "_" + name )); 30} // MIME 31} 32} catch (Exception e) {33 // TODO Auto-generated catch block34 e. printStackTrace (); 35} 36} 37}
Basic File Upload implementation

[4] Details
First question
> Some browsers send the complete file path as the file name.
C: \ Users \ lilichao \ Desktop \ day20 \ picture \ lires.jpg
> For a file name like this, we need to take a string and retrieve only the name, instead of the path information.
Use the following code to intercept a string from a file name:
If (name. contains ("\\")){
// Truncates a string if it contains
Name = name. substring (name. lastIndexOf ("\") + 1 );
}

Second question
> The uploaded file may have duplicate names. the uploaded file will overwrite the uploaded file.
> Solution: Add a unique prefix to the file name.
Only one identification _ fennu.jpg
UUID_fennu.jpg

1 // Add a unique prefix 2 String uuid = UUID. randomUUID (). toString (); // The name is repeated. The next chapter will overwrite the previous chapter 3 uuid. replace ("-","");

 

Third question
> In some cases, the size of the uploaded file must be limited.
-Set the size of a single file to 50KB:
FileUpload. setFileSizeMax (1024*50 );
-After setting the size limit for a single file, once the size limit of the uploaded file is exceeded, the following exception is thrown:
FileSizeLimitExceededException
All exceptions can be captured. When this exception occurs, an error message is set.

-Set the total size of multiple files to kb.
FileUpload. setSizeMax (1024*150 );
-When the size of multiple files exceeds the range, the following exception is thrown:
SizeLimitExceededException

1 // single file 2 fileUpload. setFileSizeMax (1024*50); 3 try {4 ...... 5} catch (FileSizeLimitExceededException e) {6 System. out. println ("the file size exceeds the limit "); 7} 8 9 // multiple files 10 set to insert multiple files 11 <input type = "file" name = "photo"> <br> 12 <input type = "file" name = "photo"> <br> 13 restrict the size of Processing 14 fileUpload. setSizeMax (1024*150); 15 try {16 ...... 17} catch (SizeLimitExceededException e) {18 System. out. println ("The overall file size exceeds the limit"); 19}
Limit File Size

Fourth Question
> When a user uploads an empty file, the file will still be saved to the hard disk.
> When saving the file, you should first judge the file size. If the size is 0, it will not be processed.

1 long size = item. getSize (); 2 if (size = 0) {3 System. out. println ("file size is blank"); 4 continue; 5} // if multiple files exist, the empty file may be in the first place, so use continue; 6 // if it is a single file, available break; 7 // The code written above is located in the for loop.

 

[5] upload Server

Files in the above Code are directly uploaded to your computer, and users cannot access the network through a browser.

If you want to access it through a browser, you can upload it to the image of the tomcat server located in eclipse. (I am using eclipse for encoding)

1. Upload the file to the server. 2. Copy the links and tc-servlet packages to the eclipse file directory. 3. 4. // copy the file to the tomcat server image, retrieve image directory 5 ServletContext servletContext = request. getServletContext (); 6 String realPath = servletContext. getRealPath ("/upload"); // location 7 File file = new File (realPath); 8 if (! File. exists () {9 file. mkdirs (); // the file does not exist. Create a file (directory) 10 // file. isDirectory () indicates that the uploaded file is a directory 11}

 

Use realPath to obtain the location of the file. Enter the file address in the browser to obtain the file.

1 localhost: 9999/web-upload/upload // enter the preceding address in the address bar of the browser to view the uploaded file (take the image as an example). 3 // localhost: 9999 indicates the tomcat port number, web-upload indicates the project name, and 4 // upload indicates the file location, 5 // 168ea717-401b-485c-9d1f-c62cfa50d36?fennu.jpg is the unique identifier randomly generated before the image name 6 6 // _

 
Complete code, including the upload Server:

Package com. neuedu. servlet; import java. io. file; import java. io. IOException; import java. util. list; import java. util. UUID; import javax. servlet. servletContext; import javax. servlet. servletException; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. apache. commons. fileupload. FileItem; import org. apache. commons. fileupload. fileUploadBase. fileSizeLimitExceededException; import org. apache. commons. fileupload. disk. diskFileItemFactory; import org. apache. commons. fileupload. servlet. servletFileUpload; @ WebServlet ("/FileUploadServlet") public class FileUploadServlet extends HttpServlet {private static final long serialVersionUID = 1L; protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// create a factory class DiskFileItemFactory factory = new DiskFileItemFactory (); // create a FileUploadServlet object, this object completes the upload function ServletFileUpload fileUpload = new ServletFileUpload (factory); fileUpload. setFileSizeMax (1024*50); // upload the file to the server, which can access ServletContext servletContext = request on the Internet. getServletContext (); String realPath = servletContext. getRealPath ("/uplo Ad "); File file = new File (realPath); if (! File. exists () {file. mkdirs (); // the file does not exist. Create a file (directory) // file. isDirectory () indicates that the uploaded file is a directory} // use this fileUpload object to parse the request to try {List <FileItem> fileList = fileUpload. parseRequest (request); for (FileItem item: fileList) {if (item. isFormField () {// represents the normal form item String name = item. getFieldName (); String value = item. getString ("UTF8"); System. out. println (name + ":" + value);} else {// indicates the uploaded file fileUpload. setFileSizeMax (1024*50); long size = item. getSize (); String contentType = item. getContentType (); String name = item. getName (); String fieldName = item. getFieldName (); if (size = 0) {System. out. println ("file size is empty"); continue;} System. out. println (size + ":" + contentType + ":" + name + ":" + fieldName); String uuid = UUID. randomUUID (). toString (); // The name is repeated. The previous uuid is overwritten in the next chapter. replace ("-", ""); try {item. write (new File (realPath + "\" + uuid + "_" + name);} catch (Exception e) {// TODO: handle exception }}// MIME} catch (FileSizeLimitExceededException e) {System. out. println ("file size exceeds limit");} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

 



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.