Experience with the use and commissioning of FileUpload components

Source: Internet
Author: User
Tags filter file system window

In the process of uploading through the use of FileUpload components, through their own debugging, summarized as follows: 1 before using the preparation, I used the Commons-fileupload-1.1-dev.jar and Commons-io-1.1-dev.jar.   Explain: Although some of the data are explained by Commons-fileupload-1.0-beta.jar and Commons-beanutils.jar, the result of debugging The display does not require Commons-beanutils.jar files, but rather because the classes in Parserequest (request) inherit from the Diskfileitem class. And he has private org.apache.commons.io.output.DeferredFileOutputStream Dfos. Such a must be used to Commons-io-1.1-dev.jar. Therefore, you need to import the package. Otherwise, there will be a classnotfound:.deferredfileoutputstream error.

2 because of the documentation involved, the file system is involved.  However, there is a certain security policy in the Java or Application server for file system access. You need to add the following permissions to your application server's security policy file: Permission Java.io.FilePermission "<<all files>>", "Read,write,delete"; Specifically, add to the. \bea\weblogic81 Erver\lib\weblogic.policy. Otherwise, you might get the following exception error: Org.apache.commons.fileupload.FileUploadException: Java.lang.reflect.InvocationTargetExceptionatorg.apache.commons.fileupload.FileUpload.createItem ( fileupload.java:615) atorg.apache.commons.fileupload.FileUpload.parseRequest (fileupload.java:474) Atorg.apache.commons.fileupload.FileUpload.parseRequest (fileupload.java:355) ....

3 for different servers, in the process of debugging will be a variety of results. This is related to the specific server.

4 because FileUpload is constantly updated, many of its methods are deprecated (this is related to the continuous improvement of the component). Through the latest help documents and information on the Internet to write a standard procedure as follows: FileUpload file: Import Java.io.ioexception;import java.io.PrintWriter;

Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.HttpServletResponse;

Import Org.apache.commons.fileupload.*;import java.util.*;import Java.util.regex.*;import Java.io.*;import Org.apache.commons.fileupload.servlet.*;import org.apache.commons.fileupload.disk.DiskFileItemFactory;

* * Create Date 2005-4-10 * * TODO to change the template for this generated file, go to the * window-preferences-Java-code style-code template * *

/** * @author gaolong1 * * TODO to change the template for this generated type annotation, go to the * window-preferences-Java-code style-code Templates */public class FileUpload extends HttpS Ervlet {

/** * Destruction of the servlet. <br> * Private String Uploadpath = "d:\\addnetfile\\"; The directory for storing uploaded files private file TempPath =new file ("d:\\addnetfile\\tmp\\"); The directory public void Destroy () {Super.destroy () for storing temporary files ()//Just puts "destroy" string in Log//Put your code here}

 /**  * The DoPost method of the servlet. <br>  *  * This is called when a form has its tag value of equals to post.  *  * @par AM request the request send by the client to the server  * @param response the "response send by the" server to the CLI ent  * @throws servletexception If an error occurred  * @throws IOException If a error occurred  */  public void DoPost (HttpServletRequest req, httpservletresponse Res) throws Servletexception, ioexception{    Res.setcontenttype ("text/html; charset=gb2312 ");   printwriter out=res.getwriter ();   system.out.println ( Req.getcontentlength ());     System.out.println (Req.getcontenttype ());    Diskfileitemfactory factory = new Diskfileitemfactory ();       //maximum size That'll be stored in memory        factory.setsizethreshold (4096);        //The location for saving data this is larger than getsizethreshold ()     &nb sp;   factory.setrepository (New File ("D:\\file\\addnetfile\\temp"));

Servletfileupload upload = new Servletfileupload (factory);        Maximum size before a fileuploadexception would be thrown Upload.setsizemax (1000000);        try{List fileitems = upload.parserequest (req); Assume we know there are two files.        The A small//text file, the second is unknown and are written to a file on//the server Iterator iter = Fileitems.iterator ();

Regular match, filter path to filename String regexp= ". +\\\\ (. +) $";

   filter out file types   string[] errortype={". exe", ". com", ". CGI", ". asp"};     Pattern p = pattern.compile (REGEXP);        while (Iter.hasnext ()) {          Fileitem item = (Fileitem) iter.next ();         //Ignore any other form information that is not a file field          if (!item.isformfield ()) {              String name = Item.getname ();              Long size = item.getsize ();              if (name==null| | Name.equals ("")) && size==0)                   continue;          Matcher m = p.matcher (name ); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp Boolean result = M.find ();         if (result) {              for (int temp=0;temp<errortype.length;temp++) {              if (M.group (1). EndsWith (errortype[temp)) {                    throw New IOException (name+ ": Wrong type");            }             }              try{

Save uploaded files to the specified directory

When you upload files to the database below, the Item.write is rewritten here (new file ("d:\\" + m.group (1)).

Out.print (name+ "" +size+ "<br>");                   catch (Exception e) {out.println (e); }

               }                else                {                  throw new IOException ("fail to upload");               }              }           }        }          catch (IOException e) {           out.println (e);         }         catch (fileuploadexception e) {              out.println (e);         }

Save uploaded files to the specified directory

When you upload files to the database below, you will overwrite this

}

/** * Initialization of the servlet. <br> * * @throws servletexception If an error occure/public void init () throws Servletexception {//Put your Code here}

The corresponding request file:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description" This is my page >

<!--<link rel= "stylesheet" type= "Text/css" href= "./styles.css" >-->


<body> <form action= "./servlet/fileupload" method= "post" enctype= "Multipart/form-data" Name= "Form1" > <input type= "File" name= "file" > <input type= "Submit" name= "submit" value= "upload" ></form> <form A Ction= "./servlet/helloword" method= "POST" > <input type= "Submit"/> </form> <form name= "uploadfor M "method=" POST "action="./servlet/fileupload "enctype=" Multipart/form-data ">

<table border= "1" width= "450" cellpadding= "4" cellspacing= "2" bordercolor= "#9BD7FF" >

&LT;TR&GT;&LT;TD width= "100%" colspan= "2" >

Name= "x" size= "1:<input" type= "File" >

</td></tr>

&LT;TR&GT;&LT;TD width= "100%" colspan= "2" >

File 2:<input name= "y" size= "+" type= "file" >

</td></tr>

&LT;TR&GT;&LT;TD width= "100%" colspan= "2" >

File 3:<input name= "z" size= "M" type= "file" >

</td></tr>

</table>

<br/><br/>

<table>

&LT;TR&GT;&LT;TD align= "center" ><input name= "upload" type= "submit" value= "Start uploading"/></td></tr>

</table>

</form>

</body>

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.