Use the fileupload component to upload files

Source: Internet
Author: User

This is a servlet application ..

The first is Web. xml.

<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" <br/> xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" <br/> xsi: schemalocation = "http://java.sun.com/xml/ns/javaee <br/> http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <br/> <servlet-Name> uploadservlet </servlet-Name> <br/> <Servlet -Class> COM. jadyer. servlet. fileuploadservlet </servlet-class> <br/> </servlet> <br/> <servlet-mapping> <br/> <servlet-Name> uploadservlet </servlet-Name> <br/> <URL-pattern>/uploadservlet </url-pattern> <br/> </servlet-mapping> <br/> <welcome-file-List> <br /> <welcome-File> upload. JSP </welcome-File> <br/> </welcome-file-List> <br/> </Web-app>

 Select the upload. jsp page of the file to be uploaded.

<% @ Page Language = "Java" pageencoding = "UTF-8" %> <br/> <% -- <br/>========== ========================================================== =================================< br/> [When uploading a file method and enctype attributes] <br/> common <form> the default method attribute of a form is get, the default enctype attribute is application/X-WWW-form-urlencoded <br/> but the form method value must be post when uploading files, enctype must be set to multipart/form-data <br/> and the enctype attribute is an essential parameter for uploading files through a form, when uploading a file, you must explicitly set it to multipart/form-data <br/> the default application/X-WWW-form-urlencoded is only used to indicate that when the form data is submitted, submitted with string Information <br/> If the multipart/form-data value is not specified, the request will be triggered. getparameter ("file ") only the file name containing the path can be obtained <br/>============================ ========================================================== =============< br/> -- %> <br/> <form action = "<% = request. getcontextpath () %>/uploadservlet "method =" Post "enctype =" multipart/form-Data "> <br/> <Table border =" 9 "> <br/> <tr> <br/> <TD> username </TD> <br/> <TD> <input type = "text" name = "username"> </TD> <br/> </tr> <br/> <TD> password </TD> <br/> <TD> <input type = "password" name = "Password "> </TD> <br/> </tr> <br/> <TD> file11 </TD> <br/> <TD> <input type = "file" name = "file11"> </TD> <br/> </tr> <br/> <TD> file22 </TD> <br/> <TD> <input type = "file" name = "file22"> </TD> <br/> </tr> <br/> <tr> <br/> <TD> </TD> <br/> <TD> <input type = "Submit" name = "Submit" value = "Upload"> </TD> <br/> </tr> <br/> </table> <br/> </form>

The result. jsp page is used to display the File Upload result.

<% @ Page Language = "Java" pageencoding = "UTF-8" %> </P> <p> <p> Step D: /program files/tomcat6/webapps/upload/uploadfile/view the uploaded file </p> <br/> <Table border = "9"> <br/> <tr> <br/> <TD> uploadresult </TD> <br/> <TD >$ {requestscope ['upload. message '] }</TD> <br/> </tr> <br/> <TD> username </TD> <br/> <TD >$ {requestscope. username }</TD> <br/> </tr> <br/> <TD> password </TD> <br/> <TD> $ {requestscope. password }</TD> <br/> </tr> <br/> <TD> file11 </TD> <br/> <TD> $ {requestscope. file11 }</TD> <br/> </tr> <br/> <TD> file22 </TD> <br/> <TD> $ {requestscope. file22 }</TD> <br/> </tr> <br/> </table>

 The core Servlet used to process file uploads

Package COM. jadyer. servlet; </P> <p> Import Java. io. file; <br/> Import Java. io. ioexception; <br/> Import Java. util. list; </P> <p> Import javax. servlet. servletexception; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. httpservletresponse; </P> <p> Import Org. apache. commons. fileupload. fileitem; <br/> Import Org. apache. commons. fileuploa D. disk. diskfileitemfactory; <br/> Import Org. apache. commons. fileupload. servlet. servletfileupload; </P> <p>/** <br/> * servlet for file upload operations <br/> * @ author Xuan Yu <br/> */<br/> public class fileuploadservlet extends httpservlet {<br/> Private Static final long serialversionuid = 7291295547319094602l; </P> <p> Public void dopost (httpservletrequest request, httpservletresponse response) <br/> throws servletexceptio N, ioexception {<br/> request. setcharacterencoding ("UTF-8"); </P> <p> // although the getrealpath () method does not agree to be used, however, it is still very useful <br/> // getrealpath ("/uploadfile") refers to the uploadfile directory under webroot <br/> string Path = request. getrealpath ("/uploadfile"); </P> <p> // create a factory. Then, set two related attributes through the factory <br/> // create a factory for disk-based file items <br/> // diskfileitemfactory factory = new diskfileitemfactory (yourmaxmemorysize, yourtempdirectory); <br/> diskfileitemfactory factory = new diskfileitemfactory (); </P> <p> // you can place files smaller than 1 MB in the memory, if the value is greater than or equal to 1 MB, it is written to the disk <br/> // set yourmaxmemorysize <br/> factory. setsizethreshold (1024*1024); <br/> // set the temporary storage directory <br/> // set yourtempdirectory <br/> fac Invalid. setrepository (new file (PATH )); </P> <p> // generate a class instance through the factory <br/> // create a new file upload handler <br/> servletfileupload upload = new servletfileupload (factory ); </P> <p> // set the size of the file to be uploaded. Unit: byte <br/> // set overall request size constraint <br/> // factory. setsizemax (yourmaxrequestsize); </P> <p> try {<br/> // parse indicates resolution, parserequest is the parsed content. <br/> // call the parserequest () method of the servletfileupload class to obtain the set of all uploaded files and parameters. <Br/> // parse the request <br/> List <fileitem> List = upload. parserequest (request); </P> <p> // traverses each fileitem object in the list object, the fileitem object represents the form parameter and the uploaded file. <br/> // then, determine whether the object is of the file type. <br/> for (fileitem item: List) {<br/> // process a regular form field <br/> If (item. isformfield () {<br/> string name = item. getfieldname (); // obtain the field name <br/> string value = item. getstring ("UTF-8"); // obtain the value of the field using the specified encoding <br/> request. setattribute (n Ame, value); // used in result. output <br/>} else {<br/> // process a file upload <br/> // if you want to process a file upload in memory, you can use code as: byte [] DATA = item. get (); <br/> If (null! = Item. getname ()&&! "". Equals (item. getname () {<br/> // use the getname () of the fileitem object () the method obtains the complete name of the uploaded file containing the suffix on the client. <br/> // getsize (), getcontenttype () of the fileitem object () you can obtain the size and type of the uploaded file. <br/> system. out. println ("Name of the uploaded file:" + item. getname (); <br/> system. out. println ("Size of the uploaded file:" + item. getsize (); <br/> system. out. println ("File Upload type:" + item. getcontenttype (); </P> <p> system. out. println ("-------------------------------------------------"); </P> <p> String value = item. getname (); <br/> int start = value. lastindexof ("//"); <br/> string filename = value. substring (start + 1); </P> <p> // use the fileitem object writer () method to save the final uploaded file. <br/> item. write (new file (path, filename); </P> <p> // used in result. display the name of the uploaded file in JSP <br/> string name = item. getfieldname (); <br/> request. setattribute (name, filename); </P> <p> request. setattribute ("upload. message "," File Uploaded successfully "); <br/>}else {<br/> r Equest. setattribute ("upload. message "," No File Uploaded "); <br/>}< br/> catch (exception ex) {<br/> ex. printstacktrace (); <br/> request. setattribute ("upload. message "," File Upload Failed "); <br/>}< br/> request. getrequestdispatcher ("result. JSP "). forward (request, response ); <br/>}< br/>/**************** [Analysis of diskfileitemfactory class ]***** **************************************** * ****************/<br/>/ /View Org. apache. commons. fileupload. disk. API document of diskfileitemfactory <br/> // observe the name of diskfileitemfactory. The translation is the factory of disk file entries, therefore, it must be related to the disk file. <br/> // diskfileitemfactory has two setter () Methods: setsizethreshold () and setrepository () method <br/>/**************** [Analysis of setsizethreshold () method ]************************************** * *********************/<br/> // setsizethreshold () in the API documentation () public void setsizethreshold (INT sizethreshol D) <br/> // Description: sets the size threshold beyond which files are written directly to disk <br/> // sets the maximum volume of uploaded files. If the size is exceeded, the file is directly written to the disk <br/> // that is, the volume of the uploaded file is specified. If the size of the uploaded file is smaller than this size, the file will be directly put into the memory. If this volume is exceeded, put the file into the disk. <br/>/****************** [Analysis of setrepository () method ]************************************** * *************************/<br/> // setrepository () the original form is public void setrepository (Java. io. file Repository) <br/> // Description: sets the directory used to temporarily store files that are larger than the configured size threshold <br/> // Translation: set the directory for temporary file storage, and the stored file is larger than the configured Threshold file <br/> // that is, setreposito Ry () is used to set a temporary directory. Once the uploaded file exceeds the specified size, save this file to this directory. <br/>/****************** [analysis of the servletfileupload class ]**** **************************************** * ******************/<br/> // The most important thing is Org. apache. commons. fileupload. servlet. servletfileupload class, which is actually used to process upload operations <br/> // in previous versions, org. apache. commons. fileupload. diskfileupload <br/> // diskfileupload Description: deprecated. use servletfileupload together with diskfileitemfactory instead <B R/> // The translation is: Use servletfileupload and diskfileitemfactory to replace diskfileupload <br/> // In the past, there was no need for a factory, and the diskfileupload instance can be created directly. However, do not use the diskfileupload class anymore. <br/> // The servletfileupload class has a constructor called servletfileupload (fileitemfactory ). It is described as follows <br/> // constructs an instance of this class which uses the supplied factory to create fileitem instances <br/> // This constructor uses the fileitemfactory type parameters. View the source code. We can see that the diskfileitemfactory class implements fileitemfactory <br/> //. Therefore, when constructing a servletfileupload instance, you can use diskfileitemfactory as the parameter of the constructor to generate an instance <br/> // so that an instance of the servletfileupload class is generated through the factory <br/> /***** * ********* [Analysis of parserequest () method ]************************************** * **************************/<br/> // provided in the servletfileupload class parserequest () method, its source code is as follows <br/> //---------------------------------------------------------------- Optional <br/> // public list/* fileitem */parserequest (httpservletrequest request) throws fileuploadexception {| <br/> // return parserequest (New servletrequestcontext (request )); | <br/> //} | <br/> // upload <br/> // The parserequest () method completes the upload process, it is a very complicated method. It receives an httpservletrequest parameter <br/> // we know that all the items passed by the client are in the request. The parserequest () will parse the request and get Java. util. list <br/> // This list encapsulates all parameters in the form passed by the client, including the file type. It encapsulates these parameters into a set so that we can use <br/> // Where/* fileitem */to indicate that the returned list is of the fileitem type. To be compatible with jdk1.4, It is not defined Using Generics <br/> // note that a fileitem corresponds to a field in the form, it is not just a file field in a form, it is not a set of all fields in the form. <br/>/***************** [analysis of the fileitem interface and its isformfield () method ]************************************** * ************/<br/> // view Org. apache. commons. fileupload. the fileitem API finds that fileitem is an interface <br/> // but we don't have to worry about the classes it is implemented, this is a benefit of interface-Oriented Programming <br/> // The fileitem interface has a Boolean isformfield () method, it is described as follows <br/> // determines whether or not a fi Leitem instance represents a simple form field <br/> // determines whether the fileitem instance represents a simple form field. <br/> // there are only two form fields, that is, the file type and non-file type. If isformfield () returns true, it indicates that it is not a file. If false is returned, it indicates that it is a file type. <br/> // Therefore, isformfield () the method can clearly determine whether the submitted form is a file type. You can use this method to completely separate the two types <br/>/****************** [fileitem. getname () method conflict with the upload of files of the same name ]******************************* * **************/<br/> // only when the item is of the file type, call the getname () method to return the real file name. If it is a common form type, call getname () to return NULL <br/> // In addition, because different browsers use different methods to parse file addresses, Some browsers automatically add paths before file names, some browsers only get the file name <br/> // so we need to manually extract the obtained file name. The final result is only the file name, not the path, in this way, the final filename is the real file name <br/> // note that, processing obtained file names is very important <br/> // to avoid file overwrites caused by different users uploading the same file, we can set the filename time here, add new date () before filename (). gettime () <br/> // in this way, the files saved on the server start with the number of milliseconds, this avoids the file name <br/> // you can also use a random number, but we need to set the random algorithm by ourselves, and when the random number is calculated, relatively high memory consumption <br/> // so currently the most common method is to use time to identify the uploaded file <br/> /************* ** [directly call the write () of the fileitem Interface () you can replace the following operations ]********************************* * ******/<br/> // outputstream OS = new fileoutputstream (new file (path, filename); <br/> // inputstream is = item. getinputstream (); <br/> // byte [] buffer = new byte [400]; <br/> // int length = 0; <br/> // while (length = is. read (buffer)> 0) {<br/> // OS. write (buffer, 0, length); <br/>//} <br/> // OS. close (); <br/> // is. close (); <br/> /*********************************** **************************************** *****************************/

 When the file is uploaded successfully, it will be saved in the local hard disk.

That is, In the localdisk // tomcat6 // webapps // upload // uploadfile // folder

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.