Fileupload File Upload

Source: Internet
Author: User

When using Java to develop file uploads, there are many different tools on the network. However, if development is required every time, this process is a waste of time for users. Therefore, we need to select one of the File Upload components suitable for ourselves, and then further package them to form our own development tool class. Below I encapsulate fileupload for my project.

Fileupload is a component of Apache, to use fileupload, you need to use the following two jar: commons-fileupload-1.3.1.jar, commons-io-1.1.jar (version is not the same, may be the relevant jar package is inconsistent, you can download according to the latest ).

Download the relevant jar package, use eclipse to create a dynamic web project, and add the jar to the WEB-INF/lib.

Since the fileupload component is very simple to use, you can refer to the API on the official website. This is the last way to learn fileupload. Link: fileupload

The following shows my own classes and code:

Package net. itaem. servlet; import Java. io. file; import Java. io. ioexception; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import Java. util. UUID; import javax. servlet. servletconfig; import javax. servlet. servletcontext; 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. fileuploadexception; import Org. apache. commons. fileupload. disk. diskfileitemfactory; import Org. apache. commons. fileupload. servlet. servletfileupload;/*** the base class for file upload. This class can be inherited * in the configuration file. You must configure the relevant upload attributes *. This is a parent class that stores files, however, for common form fields, the subclass is used to implement * each subclass must implement the processnormalfield (fileitem) Method * The template design mode is used here... * **/Public abstract class fileuploadservletbase extends httpservlet {/*****/Private Static final long serialversionuid = 1l; // save the file folder Private Static string savedir = NULL; // cache size Private Static int tempcachedsize = 20480; // Private Static string [] permittedfiletype = NULL; // size of a single file Private Static int filesize = 20480; // maximum Private Static int maxsize = 204800; // Private Str Ing savepath; // Save the rivate map of the uploaded file <string, string> uploadedmap = new hashmap <string, string> (); @ overrideprotected void doget (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {dopost (req, resp) ;}@ pull ("rawtypes") @ overrideprotected void dopost (httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {// set the encoding req. setcharact Erencoding ("UTF-8"); resp. setcharacterencoding ("UTF-8"); // create a diskfileitemfactorydiskfileitemfactory factory = new diskfileitemfactory (); factory. setrepository (new file (savepath); // configure the Save path factory. setsizethreshold (tempcachedsize); // configure the cache size // create a servletfileuploadservletfileupload upload = new servletfileupload (factory); upload. setsizemax (maxsize); // set the overall form size upload. setfilesizemax (filesize); // set the size of a single file/ /Process the Form Try {list <fileitem> items = upload. parserequest (req); iterator itemsiterator = items. iterator (); While (itemsiterator. hasnext () {fileitem = (fileitem) itemsiterator. next (); If (! Fileitem. isformfield () {// file field // remove the file type boolean uploadedflag = false; For (INT I = 0; I <permittedfiletype. length; I ++) {If (permittedfiletype [I]. contains (fileitem. getcontenttype () {uploadedflag = true; break ;}}// if the file allows upload, save the file to the specified upload folder if (uploadedflag) {string type = fileitem. getname (). substring (fileitem. getname (). lastindexof (". "); file uploadedfile = newfile (type); // Save the filefileitem. write (upload Edfile); // put the file name in a mapuploadedmap. put (fileitem. getfieldname (), uploadedfile. getCanonicalPath () ;}} else {// common form field processnormalfield (fileitem) ;}// after uploading, perform related operations, such as associating a database, alternatively, you can save the uploaded file name in an XML or other file, such as finishedprocess ();} catch (fileuploadexception e) {e. printstacktrace ();} catch (exception e) {e. printstacktrace () ;}}/*** get a random string as the file name to upload, prevent the file from being rewritten * @ return to return a unique random string */Public String getrando Mfilename () {UUID filenameuuid = UUID. randomuuid (); Return filenameuuid. tostring () ;}@ overridepublic void Init () throws servletexception {super. init ();}/*** initialize the servlet and read the parameters in the configuration file **/@ overridepublic void Init (servletconfig config) throws servletexception {If (config. getinitparameter ("savedir") = NULL) {Throw new runtimeexception ("The savedir parameter cannot be blank");} else {savedir = config. getinitparameter ("savedir "). trim ();} If (config. getinitparameter ("permittedfiletype") = NULL) {Throw new runtimeexception ("The permittedfiletype parameter cannot be blank");} else {permittedfiletype = config. getinitparameter ("permittedfiletype "). trim (). split (",");} If (config. getinitparameter ("filesize") = NULL) {Throw new runtimeexception ("The filesize parameter cannot be blank");} else {filesize = integer. parseint (config. getinitparameter ("filesize "). trim ();} If (config. getinitparamet Er ("maxsize") = NULL) {Throw new runtimeexception ("The maxsize parameter cannot be blank");} else {maxsize = integer. parseint (config. getinitparameter ("maxsize "). trim ();} If (config. getinitparameter ("tempcachedsize") = NULL) {Throw new runtimeexception ("The tempcachedsize parameter cannot be blank");} else {tempcachedsize = integer. parseint (config. getinitparameter ("tempcachedsize "). trim ();} // create a folder. If the folder does not exist, savedir = createsavedir (config. getservletcon Text (), savedir );} /*** create a folder * @ Param context request context * @ Param dirname folder name * @ return returns the path of the folder in the current project **/private string createsavedir (servletcontext context, string dirname) {string contextpath = context. getrealpath ("/"); // obtain the project's savepath = contextpath + dirname; file dir = new file (savepath); If (! Dir. exists () {// if the file does not exist, create the folder dir. mkdir (); Return savepath;} else {If (dir. isdirectory () {// The folder already exists and is a folder. Return return savepath;} else {Throw new runtimeexception ("this file" + savepath + "already exists, please reconfigure the name of the folder to save the uploaded file ") ;}}/*** this is an abstract class, implemented by the Base class, this method is mainly used to process common forms * use the template design mode... * process common form fields * @ Param fileitem common form fields **/public abstract void processnormalfield (fileitem ); /*** @ Param type: the file type * is a random file. The file suffix * @ return random file **/Public file newfile (string type) is determined by type) {return new file (savepath + file. separator + getrandomfilename () + type);}/*** returns all file names as a map * Key: Form domain name * value: upload File name * @ return returns the map of all uploaded files **/Public Map <string, string> getuploadedmap () {return uploadedmap ;} /*** find the file name after the file is uploaded through the form field * @ Param filedname form domain name * @ return name of the uploaded file */Public String getuploadedname (string fieldname) {If (fieldname = NULL) return NULL; return uploadedmap. get (fieldname);}/*** the form has been processed. Next, process the related operations, for example, operations such as saving the uploaded file name to the database * usually related to the */public abstract void finishedprocess ();}

From the class definition, we can see that this class is an abstract class and uses the method template design pattern.

The following is a simple implementation class:

Package net. itaem. servlet; import Java. util. map; import Org. apache. commons. fileupload. fileitem; /*** a class for file upload * the common form field ***/public class genericfileuploadservlet extends fileuploadservletbase {/***/Private Static final long serialversionuid = 155452356%458695l; @ overridepublic void processnormalfield (fileitem) {system. out. println (fileitem. getfieldname () + "--->" + fileitem. getstring (); // do something here}/*** after the form is processed, the related operations are processed, for example, the Operation D **/@ overridepublic void finishedprocess () {Map <string, string> uploadedmap = super. getuploadedmap (); // print the Upload File name corresponding to each form field for (string fieldname: uploadedmap. keyset () {system. out. println (fieldname + "--->" + uploadedmap. get (fieldname ));}}}

Summary:

In the implementation class genericfileuploadservlet, we can process common form fields or handle uploaded files. So with this design, we can manually configure in the servlet configuration every time: Save the folder name, cache size, support for upload type, maximum support for upload size, the size of a single file. My configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  <display-name></display-name>    <servlet>      <servlet-name>fileupload</servlet-name>      <servlet-class>net.itaem.servlet.GenericFileUploadServlet</servlet-class>            <init-param>          <param-name>tempSaveDir</param-name>          <param-value>temp_upload</param-value>      </init-param>            <init-param>          <param-name>saveDir</param-name>          <param-value>upload</param-value>      </init-param>            <init-param>          <param-name>tempCachedSize</param-name>          <param-value>2048000</param-value>      </init-param>           <init-param>          <param-name>permittedFileType</param-name>          <param-value>text/html,application/octet-stream,video/mp4</param-value>      </init-param>             <init-param>          <param-name>fileSize</param-name>          <param-value>204800000</param-value>      </init-param>             <init-param>          <param-name>maxSize</param-name>          <param-value>20480000</param-value>      </init-param>             <load-on-startup>10</load-on-startup>  </servlet>    <servlet-mapping>      <servlet-name>fileupload</servlet-name>      <url-pattern>/fileupload.do</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

Note:

When saving an uploaded file, note that the file name must be unique. UUID tool class is used for generation. Haha, this class is in the Java. util package.

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.