First, the file upload
1. Basic upload of files
For file upload, the browser in the process of uploading the file as a stream to the server side, if directly using the servlet to get the input stream of the uploaded file and then parse the request parameters inside is more trouble, So the general choice is to use the Apache Open Source Tool common-fileupload This file upload component. This common-fileupload upload component jar package can go to Apache official web surface download, can also be found under the Lib folder of struts, struts upload function is based on this implementation. Common-fileupload is dependent on Common-io for this package, so you need to download this package as well.
index.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
message.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Uploadservlet.java
/** * Processing upload data * @date 2016-4-17 */public class Uploadservlet extends Httpservlet{public void doget (HttpServletRequest req,h Ttpservletresponse resp) throws servletexception,ioexception{//get the file to save the directory, upload files stored in the Web-inf directory, not allow direct access to the outside world, Secure uploading of files string savepath = 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 create");//Create Directory File.mkdir ();} String message = ""; try{//using the 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);// To resolve the upload file name of the Chinese garbled upload.setheaderencoding ("UTF-8");//3, to determine whether the submitted data is the upload form data if (!). Servletfileupload.ismultipartcontent (req)) {return;} 4, using the Servletfileupload parser to parse the upload data, the results of the analysis returned is a list<fileitem> collection, each fileitem corresponding to a form form input items List<fileitem > list = upload.parserequest (req); for (Fileitem fileitem:list) {if (fileitem.iSformfield ()) {//If the data in the Fileitem is encapsulated in a normal input string fieldName = Fileitem.getfieldname ();//solve the problem of normal input data in Chinese garbled string Filevalue = fileitem.getstring ("UTf-8"); System.out.println (fieldName + "=" + Filevalue);} else{//If the upload file is encapsulated in Fileitem, string fileName = Fileitem.getname (); if (fileName = = NULL | | Filename.trim (). Equals ("")) { Continue;} Process the path portion of the file name that gets to the upload, leaving only the file name part of filename = filename.substring (filename.lastindexof ("\ \") + 1);// Gets the input stream of the uploaded file in the item inputstream in = Fileitem.getinputstream ();//create a file output stream FileOutputStream fos = new FileOutputStream ( Savepath + "\ \" + fileName);//Read and write file int len = 0;byte[] buffer = new Byte[1024];while ((len = in.read (buffer))! =-1) {Fos.writ E (Buffer,0,len);} In.close (); Fos.close ();//delete the temporary file generated when processing file upload fileitem.delete (); message = "File Upload succeeded!" ";}}} catch (Exception e) {message= "File upload failed! "; E.printstacktrace ();} Req.setattribute ("message", message); Req.getrequestdispatcher ("/message.jsp"). Forward (REQ,RESP);} public void DoPost (HttpServletRequest req,httpservletresponse resp) throws ServletexceptIon,ioexception{doget (REQ,RESP);}}
Results:
2. File Upload optimization
Although the above code can successfully upload the file to the server above the specified directory, but the file upload function has a lot of attention to the small details of the problem, the following points out the need to pay special attention to
(1) In order to ensure the security of the server, upload files should be placed in the outside world can not directly access the directory, such as placed in the Web-inf directory.
(2) To prevent the occurrence of file coverage, to upload a file to generate a unique file name.
(3) To prevent too many files under a directory, the hash algorithm is used to break up the storage.
(4) To limit the maximum number of uploaded files.
(5) To limit the type of uploaded files, when you receive the upload file name, determine whether the suffix name is legitimate.
to address the above 5 points of detail, we will improve the Uploadhandleservlet, the improved code is as follows
/** * Processing Upload data * * @date 2016-4-17 */public class Uploadservlet extends Httpservlet{public void doget (HttpServletRequest re Quest,httpservletresponse response) throws servletexception,ioexception{//get the saved directory of uploaded files and store the uploaded files in the Web-inf directory. Do not allow direct access to the outside world, secure the uploading of files string savepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");// Temporary files generated at upload Save directory string temppath = This.getservletcontext (). Getrealpath ("/web-inf/temp"); File Tmpfile = new file (TempPath), if (!tmpfile.exists ()) {//Create temp directory Tmpfile.mkdir ();} Message prompt String message = ""; 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 buffer, and when the uploaded file size exceeds the size of the buffer, a temporary file is generated to be stored in the specified temporary directory. Factory.setsizethreshold (1024 * 100);//sets the buffer size to 100KB, if not specified, 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:" + Pcontentlength + ", currently processed:" + Pbytesread);}); /resolve the upload file name of the Chinese garbled upload.setheaderencoding ("UTF-8");//3, to determine whether the data submitted is to upload the form data if (!). Servletfileupload.ismultipartcontent (Request)) {//Get data return in traditional way;} Set the maximum size of the uploaded individual file, currently set to 1024*1024 bytes, i.e. 1mbupload.setfilesizemax (1024 * 1024);//Set the maximum number of uploaded files, max = Simultaneous uploading of the maximum value of the size of multiple files is currently set to 10mbupload.setsizemax (1024 * 1024 * 10);//4, using the Servletfileupload parser to parse the uploaded data, the result of the parse is to return a list <FileItem> set, each fileitem corresponds to the entry of a form form list<fileitem> list = upload.parserequest (request); for (Fileitem Item:list) {//If the data encapsulated in Fileitem is a normal input item (Item.isformfield ()) {String name = Item.getfieldname ();/ Solve the problem of normal input data in Chinese garbled string value = Item.getstring ("UTF-8");//value = new String (value.getbytes ("iso8859-1"), "UTF-8"); SYSTEM.OUT.PRINTLN (name + "=" + value);} else{//if the file name of the uploaded file//Get uploaded is encapsulated in Fileitem, String filename = Item.getname (); SYSTEM.OUT.PRINTLN (filename), if (filename = = NULL | | Filename.trim (). Equals ("")) {continue;} Path to the file name of the uploaded file to be processedsection, keep only the filename part of filename = filename.substring (filename.lastindexof ("\ \") + 1);//Get the file name extension string fileextname = Filename.substring (Filename.lastindexof (".") + 1);//If you need to limit the file types that you upload, you can determine whether the file type you uploaded is legitimate System.out.println the file's extension (" The extension of the uploaded file is: "+ fileextname);//Gets the input stream of the uploaded file in the item inputstream in = Item.getinputstream ();//Gets the file save name string savefilename = Makefilename (filename);//Get File Save directory String realsavepath = Makepath (Savefilename,savepath); FileOutputStream out = new FileOutputStream (Realsavepath + "\" + savefilename); byte buffer[] = new Byte[1024];int len = 0 ; while (len = in.read (buffer)) > 0) {out.write (Buffer,0,len);} In.close (); Out.close (); message = "File Upload succeeded!" ";}}} catch (Fileuploadbase.filesizelimitexceededexception e) {e.printstacktrace (); Request.setattribute ("Message", " Single file exceeded maximum!!! "); 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 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) ;} private string Makefilename (string filename) {//To prevent file coverage from occurring, create a unique file name for the upload file return Uuid.randomuuid (). toString () + "_ "+ filename;} private string Makepath (String filename,string savepath) {//Gets the hashcode value of the file name, and the resulting filename is the address of the string object in memory int hashcode = Filename.hashcode (); int dir1 = hashcode & 0xf; 0--15int Dir2 = (hashcode & 0xf0) >> 4; 0-15//constructs a new save directory string dir = Savepath + "\ \" + dir1 + "\ \" + Dir2; File File = new file (dir), if (!file.exists ()) {file.mkdirs ();} return dir;} public void DoPost (HttpServletRequest req,httpservletresponse resp) throws Servletexception,ioexception{doget (req, RESP);}}
Javaweb Summary (10)-File upload and download