The most detailed file upload download example detailed (recommended) _java

Source: Internet
Author: User
Tags create directory file upload mkdir uuid

In the Web application system development, the file uploads and the downloading function is the very commonly used function, today says the Javaweb file uploads and the downloading function realization.

For file upload, the browser upload the file in the form of streaming files to the server side, if the direct use of the servlet to obtain upload file input stream and then parse the request parameters inside is more trouble, So generally choose to use the Apache Open Source Tool common-fileupload This file upload component. This common-fileupload upload component jar package can go to the Apache online download, also can be found under the Lib folder of struts, struts upload function is based on this implementation. Common-fileupload is dependent on the Common-io package, so it is also necessary to download the package.

One, the development environment constructs

Create a Fileuploadanddownload project, add the associated jar package for the Apache commons-fileupload File Upload component, as shown in the following illustration:

  

Second, the implementation of file upload

2.1. File upload page and message prompt page

The code for the Upload.jsp page is as follows:

<%@ page language= "java" pageencoding= "UTF-8"%> 
<! DOCTYPE html> 
 
 

2.2, processing file upload of the servlet

The code for Uploadhandleservlet is as follows:

Package Me.gacl.web.controller; 
Import Java.io.File; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.util.List; 
Import javax.servlet.ServletException; 
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.disk.DiskFileItemFactory; 
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;  public class Uploadhandleservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {//Get upload File save directory, will upload the file stored in the Web-inf directory, do not allow direct access to the outside world, to ensure that the upload file security String Savepat 
h = This.getservletcontext (). Getrealpath ("/web-inf/upload"); 
File File = new file (Savepath); 
Determine if the saved directory for the uploaded file exists if (!file.exists () &&!file.isdirectory ()) {System.out.println (savepath+ "directory does not exist, need to be created"); Create directory File.mkdir ();
}//message prompts String messages = ""; 
try{///Use Apache File Upload component to process file upload steps://1, create a diskfileitemfactory factory diskfileitemfactory factory = new Diskfileitemfactory (); 
2, create a file upload parser servletfileupload upload = new Servletfileupload (factory); 
Solve the upload file name of Chinese garbled upload.setheaderencoding ("UTF-8"); 3, to determine whether the data submitted is uploaded form data if (! 
Servletfileupload.ismultipartcontent (Request)) {//Get data return in the traditional way; //4, using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> set, each fileitem corresponding to a form of the input item List<fileitem 
> list = upload.parserequest (request); 
for (Fileitem item:list) {//If the data in Fileitem is encapsulated in the normal input item if (Item.isformfield ()) {String name = Item.getfieldname (); 
Solve the Chinese garbled problem of the data of the normal input item String value = item.getstring ("UTF-8"); 
Value = new String (value.getbytes ("iso8859-1"), "UTF-8"); 
SYSTEM.OUT.PRINTLN (name + "=" + value); 
}else{//If the Fileitem is encapsulated in the upload file//Get uploaded file name, String filename = Item.getname (); 
SYSTEM.OUT.PRINTLN (filename); 
if (Filename==null | | Filename.trim (). Equals ("")) {continue; }//Note: NoThe same browser submitted the file name is not the same, some browsers submitted to the file name is with the path, such as: C:\a\b\1.txt, and some just simple file name, such as: 1.txt//processing to obtain the upload file filename of the path section, only keep the filename part filename = 
Filename.substring (Filename.lastindexof ("\") +1); 
Gets the input stream inputstream in = Item.getinputstream () of the uploaded file in item; 
Create a file output stream FileOutputStream out = new FileOutputStream (Savepath + "\" + filename); 
Create a buffer byte buffer[] = new byte[1024]; 
Determine if the data in the input stream has been read out of the identity int len = 0; The loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is also data while (Len=in.read (buffer) >0) {// 
Writes the data of the buffer to the specified directory (Savepath + "\" + filename) using the FileOutputStream output stream out.write (buffer, 0, Len); 
//Close the input stream in.close (); 
Turn off the output stream out.close (); 
Deletes the temporary files generated when processing file uploads item.delete (); message = "File Upload success!" 
"; }}catch (Exception e) {message= file upload failed! 
"; 
E.printstacktrace (); 
} request.setattribute ("message", message); 
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception {doget (request, response);  } 
}

Registering in the Web.xml file Uploadhandleservlet

<servlet> 
<servlet-name>UploadHandleServlet</servlet-name> 
<servlet-class> me.gacl.web.controller.uploadhandleservlet</servlet-class> 
</servlet> 
<servlet-mapping > 
<servlet-name>UploadHandleServlet</servlet-name> 
<url-pattern>/servlet/ Uploadhandleservlet</url-pattern> 

The operation effect is as follows:

After the file was uploaded successfully, the uploaded file was saved in the upload directory in the Web-inf directory, as shown in the following figure:

2.3, the File upload details

Although the above code can successfully upload the file to the designated directory above the server, but the file upload function has a lot of attention to the small details of the problem, the following points need to pay special attention to

1, in order to ensure server security, upload files should be placed in the outside can not directly access the directory, such as in the Web-inf directory.

2, in order to prevent the occurrence of file coverage, to upload files to produce a unique file name.

3. To prevent the occurrence of too many files under a directory, use the hash algorithm to break up the storage.

4, to limit the upload file maximum value.

5, to limit the type of upload file, when the upload file name, determine whether the suffix name is legitimate.

In response to the above 5 points of detail, we will improve the Uploadhandleservlet, the improved code is as follows:

Package Me.gacl.web.controller; 
Import Java.io.File; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
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 Org.apache.commons.fileupload.FileItem; 
Import Org.apache.commons.fileupload.FileUploadBase; 
Import Org.apache.commons.fileupload.ProgressListener; 
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory; 
Import Org.apache.commons.fileupload.servlet.ServletFileUpload; /** * @ClassName: Uploadhandleservlet * @Description: TODO (Describe the role of this class in one sentence) * @author: Aloof Wolf * @date: 2015-1-3 afternoon 11:35:5 0 * */public class Uploadhandleservlet extends HttpServlet {public void doget (HttpServletRequest request, Httpservle Tresponse response) throws Servletexception, IOException {//Get upload File save directory, the uploaded files are stored in the Web-inf directory, do not allowExternal direct access to ensure that the upload file security String Savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload"); 
Temporary files generated on upload save directory String TempPath = This.getservletcontext (). Getrealpath ("/web-inf/temp"); 
File Tmpfile = new file (TempPath); 
if (!tmpfile.exists ()) {//Create temporary directory Tmpfile.mkdir (); 
}//message prompts String messages = ""; 
try{///Use Apache File Upload component to process file upload steps://1, create a diskfileitemfactory factory diskfileitemfactory factory = new Diskfileitemfactory (); 
Sets the size of the factory's buffer, and when the uploaded file size exceeds the buffer size, a temporary file is generated to be stored in the specified temporary directory. 
Factory.setsizethreshold (1024*100)//Set buffer size of 100KB, if unspecified, then the buffer size defaults to 10KB//Set the Save directory for temporary files generated when uploading 
Factory.setrepository (tmpfile); 
2, create a file upload parser servletfileupload upload = new Servletfileupload (factory); Monitor File Upload Progress Upload.setprogresslistener (new Progresslistener () {public void update (long pbytesread, long pcontentlength, 
int arg2) {System.out.println ("File size is: + Pcontentlength +", currently processed: "+ pbytesread);" /** * File size is: 14608, currently processed: 4096 file size is: 14608, currently processed: 7367 file size is: 14608, currently processed: 11419 file size is: 14608, currently processed: 14608 */}}); 
Solve the upload file name of Chinese garbled upload.setheaderencoding ("UTF-8"); 3, to determine whether the data submitted is uploaded form data if (! 
Servletfileupload.ismultipartcontent (Request)) {//Get data return in the traditional way; 
//Set the maximum size of a single file to upload, is currently set to 1024*1024 Byte, that is, 1MB Upload.setfilesizemax (1024*1024); 
Set the maximum number of uploaded files, maximum = The maximum size of multiple files uploaded at the same time, currently set to 10MB Upload.setsizemax (1024*1024*10); 4, using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> set, each fileitem corresponding to a form of the input items List<fileitem 
> list = upload.parserequest (request); 
for (Fileitem item:list) {//If the data in Fileitem is encapsulated in the normal input item if (Item.isformfield ()) {String name = Item.getfieldname (); 
Solve the Chinese garbled problem of the data of the normal input item String value = item.getstring ("UTF-8"); 
Value = new String (value.getbytes ("iso8859-1"), "UTF-8"); 
SYSTEM.OUT.PRINTLN (name + "=" + value); 
}else{//If the Fileitem is encapsulated in the upload file//Get uploaded file name, String filename = Item.getname (); 
SYSTEM.OUT.PRINTLN (filename); 
if (Filename==null | | Filename.trim (). Equals ("")) {continue; //Note: Different browsers submit the file name is not the same, some browsers submit the filename is a path, such as: C:\a\b\1.txt,And some just simple file names, such as: 1.txt//processing acquired upload file filename of the path section, only keep the filename part filename = filename.substring (filename.lastindexof ("\") +1); Get upload file extension String fileextname = filename.substring (Filename.lastindexof (".") 
+1); 
If you need to limit the file type of upload, you can use the file extension to determine whether the file type uploaded is legitimate System.out.println ("uploaded file extension is:" +fileextname); 
Gets the input stream inputstream in = Item.getinputstream () of the uploaded file in item; 
Get file saved name String savefilename = makefilename (filename); 
Get File Save directory String Realsavepath = Makepath (Savefilename, Savepath); 
Create a file output stream FileOutputStream out = new FileOutputStream (Realsavepath + "\" + savefilename); 
Create a buffer byte buffer[] = new byte[1024]; 
Determine if the data in the input stream has been read out of the identity int len = 0; The loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is also data while (Len=in.read (buffer) >0) {// 
Writes the data of the buffer to the specified directory (Savepath + "\" + filename) using the FileOutputStream output stream out.write (buffer, 0, Len); 
//Close the input stream in.close (); 
Turn off the output stream out.close (); 
Deletes the temporary files generated when processing file uploads//item.delete (); message = "File Upload success!" 
"; }}}catch (Fileuploadbase.filesizelimitexCeededexception e) {e.printstacktrace (); Request.setattribute ("Message", "Single file exceeds maximum value!!! 
"); 
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); 
Return 
}catch (fileuploadbase.sizelimitexceededexception e) {e.printstacktrace (); Request.setattribute ("message", "The total size of the uploaded file exceeds the maximum value of the limit!!! 
"); 
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); 
Return }catch (Exception e) {message= file upload failed! 
"; 
E.printstacktrace (); 
} request.setattribute ("message", message); 
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); /** * @Method: Makefilename * @Description: Generate uploaded file name, file name: uuid+ "_" + the original name of the file * @Anthor: Lonely Wolf * @param filename File Original  
Name * @return Uuid+ "_" + the original name of the file/private string Makefilename (string filename) {//2.jpg//To prevent file overwrite, to generate a unique file name for the uploaded file 
Return Uuid.randomuuid (). toString () + "_" + filename; /** * To prevent a directory from appearing under too many files, use the hash algorithm to break up the storage * @Method: Makepath * @Description: * @Anthor: Lonely Wolf * @param filenameName, to generate a storage directory based on the filename * @param savepath file storage path * @return New storage directory/private string Makepath (String filename,string savepath) { 
Get the filename of the hashcode value, get the filename of this string object in memory of the address int hashcode = Filename.hashcode (); int dir1 = hashcode&0xf; 0--15 int dir2 = (hashcode&0xf0) >>4; 0-15//Construct new save directory String dir = savepath + "\" + Dir1 + "\" + Dir2; 
Upload\2\3 upload\3\5//file can represent either a file or a directory file = new file (dir); 
If the directory does not exist if (!file.exists ()) {///Create directory File.mkdirs (); 
} return dir; public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {D 
Oget (request, response);  } 
}

In response to the above 5 points to improve the small details of the problem, our file upload function even more perfect.

Third, File download

3.1. List the file resources available for download

We want to provide the Web application system file resources to the user to download, first of all we have a page listing the uploaded files in the directory of all the files, when the user clicks on the file to download hyperlinks when the download operation, write a listfileservlet, Used to list all downloaded files in the Web application system.

The code for Listfileservlet is as follows:

Package Me.gacl.web.controller; 
Import Java.io.File; 
Import java.io.IOException; 
Import Java.util.HashMap; 
Import Java.util.Map; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; /** * @ClassName: Listfileservlet * @Description: List all downloaded files in the Web system * @author: The Lonely Wolf * @date: 2015-1-4 Afternoon 9:54:40 * * * p Ublic class Listfileservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respo NSE) throws Servletexception, IOException {//Get upload file directory String Uploadfilepath = This.getservletcontext (). Getrealpath ("/ 
Web-inf/upload "); 
Store the filename to download map<string,string> filenamemap = new hashmap<string,string> (); Recursively iterates through all the files and directories in the FilePath directory, storing the file names in the Map collection listfile (new file (Uploadfilepath), filenamemap); 
File can represent either a file or a directory//map collection to the listfile.jsp page for display request.setattribute ("fileNameMap", fileNameMap); Request.getrequesTdispatcher ("/listfile.jsp"). Forward (request, response);  /** * @Method: ListFile * @Description: recursively traverse all files in the specified directory * @Anthor: Aloof Wolf * @param file represents a file, also represents a file directory * @param map The Map collection that stores the file name */public void ListFile (file file,map<string,string> Map) {//If file represents not a file, but a directory if (!file.isfile 
()) {//list all files and directories under this directory file files[] = File.listfiles (); 
Traversal files[] Array for (File f:files) {//recursive listfile (F,MAP); }else{/** * Process filename, uploaded file is renamed as uuid_ filename, remove uuid_ part of filename file.getname (). IndexOf ("_") retrieves the first occurrence of the "_" character in the string. If the file name is similar to: 9349249849-88343-8344_ _ van _ to AVI so File.getname (). substring (File.getname (). IndexOf ("_") +1) after processing can be obtained AH _ every _ 
Up to AVI part/String realname = File.getname (). substring (File.getname (). IndexOf ("_") +1); 
File.getname () Gets the original name of the file, which is unique, so it can be used as a key,realname after the name is processed, and may be repeated map.put (File.getname (), realname);  
} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { 
Doget (request, response);  } 
}

Here is a brief listfileservlet of the ListFile method, ListFile method is used to list all the files in the directory, ListFile method internal use of recursion, in the actual development, we will certainly create a table in the database, It will store the uploaded file name and the file's specific directory, we can know the file directory through the query table, is not required to use recursive operation, this example is because the database is not used to store uploaded file names and files of the specific storage location, The location of the uploaded file is also used to scatter the storage of the hash algorithm, so, recursion is needed, and in recursion, the acquired filename is stored in a map set that is passed from the outside to the ListFile method, so that all files are stored in the same map collection.

Configuring Listfileservlet in Web.xml files

<servlet> 
<servlet-name>ListFileServlet</servlet-name> 
<servlet-class> me.gacl.web.controller.listfileservlet</servlet-class> 
</servlet> 
<servlet-mapping> 
<servlet-name>ListFileServlet</servlet-name> 
<url-pattern>/servlet/listfileservlet </url-pattern> 

The listfile.jsp page for the display download file is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% 
@taglib prefix= "C" uri= "http://" Java.sun.com/jsp/jstl/core "%> 
<! DOCTYPE html> 
 
 

Accessing Listfileservlet, you can display the file resources provided to users in the Listfile.jsp page as shown in the following illustration:

3.2, the implementation of file download

Write a servlet,downloadservlet code for handling file downloads as follows:

Package Me.gacl.web.controller; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.IOException; 
Import Java.io.OutputStream; 
Import Java.net.URLEncoder; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; public class Downloadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp Onse) throws Servletexception, IOException {//get the filename to download String filename = request.getparameter ("filename");//23239283 
-92489-avatar. avi FileName = new String (filename.getbytes ("iso8859-1"), "UTF-8"); The uploaded files are all stored in subdirectories under the/web-inf/upload directory, String Filesaverootpath=this.getservletcontext (). Getrealpath ("/web-inf/ 
Upload "); 
Locate the file's directory by file name String Path = Findfilesavepathbyfilename (Filename,filesaverootpath); 
Get the file that you want to download = filename = new file (path + "\" + fileName); If the file does not exist if (!file.exists ()) {Request.setattribute ("MesSage "," The resource you are downloading has been deleted!! 
"); 
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); 
Return 
//process filename String realname = filename.substring (Filename.indexof ("_") +1); Set the response header to control the browser to download the file Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (Realname, "") 
UTF-8 ")); 
Read the file to be downloaded, save to the file input stream FileInputStream in = new FileInputStream (path + "\" + fileName); 
Create output stream OutputStream out = Response.getoutputstream (); 
Create buffer byte buffer[] = new byte[1024]; 
int len = 0; 
Loops read the contents of the input stream into the buffer while (len=in.read (buffer) >0) {//output buffer contents to the browser, implementation file download out.write (buffer, 0, Len); 
//close file Input stream in.close (); 
Turn off the output stream out.close (); /** * @Method: Findfilesavepathbyfilename * @Description: Find the path to the file you want to download by file name and store upload file root directory * @Anthor: Lonely Wolf * @param file Name to download the filename * @param saverootpath upload file to save the root directory, that is, the/web-inf/upload directory * @return The storage directory of the files to download/public String Findfilesave Pathbyfilename (String filename,string saverootpath) {int hashcode = Filename.hashcoDe (); int dir1 = hashcode&0xf; 0--15 int dir2 = (hashcode&0xf0) >>4; 0-15 String dir = saverootpath + "\" + Dir1 + "\" + Dir2; 
Upload\2\3 upload\3\5 file = new file (dir); 
if (!file.exists ()) {//Create directory File.mkdirs (); 
} return dir; public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {D 
Oget (request, response);  } 
}

Configuring Downloadservlet in Web.xml files

<servlet> 
<servlet-name>DownLoadServlet</servlet-name> 
<servlet-class> me.gacl.web.controller.downloadservlet</servlet-class> 
</servlet> 
<servlet-mapping> 
<servlet-name>DownLoadServlet</servlet-name> 
<url-pattern>/servlet/downloadservlet </url-pattern> 

Click on the "Download" hyperlink, the request submitted to the Downloadservlet on the line processing can be implemented file download, the operation effect as shown in the following figure:

  

From the results of the operation can be seen, our file download function has been able to download the file normally.

The above is a small series to introduce the most detailed file upload download examples (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.