有關FileUpload組件的使用和調試的經驗

來源:互聯網
上載者:User

在通過使用FileUpload組件上傳的過程中,通過自己的調試,總結如下:1)使用之前的準備,我用的是commons-fileupload-1.1-dev.jar和commons-io-1.1-dev.jar。   解釋一下:儘管有的資料解釋是commons-fileupload-1.0-beta.jar和commons-beanutils.jar,通過調試的結果   顯示並不是需要commons-beanutils.jar檔案,而是由於在parseRequest(request)的類有關繼承於DiskFileItem類。而他有private  org.apache.commons.io.output.DeferredFileOutputStream dfos。這樣的就必須使用到commons-io-1.1-dev.jar。因此需要匯入該包。否則就出classNotFound:.DeferredFileOutputStream的錯誤。

2)由於涉及檔案,就涉及到檔案系統。然而在java或應用伺服器中對於檔案系統的訪問,就有一定的安全性原則。  需要將下列許可權添加到您應用程式伺服器的安全性原則檔案中:permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";具體是添加到..\bea\weblogic81 erver\lib\weblogic.policy中的.否則會可能出如下異常錯誤: 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)對於不同的伺服器,在調試的過程中會出各種不一樣的結果。這個與具體的伺服器有關。

4)由於FileUpload在不斷的更新版本,它的很多方法已經不推薦使用了(這與該組件的不斷的改進有關)。通過對最新的協助文檔和網上的資料寫了一個標準的程式如下:fileUpload檔案: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;

/* * 建立日期 2005-4-10 * * TODO 要更改此產生的檔案的模板,請轉至 * 視窗 - 喜好設定 - Java - 代碼樣式 - 代碼模板 */

/** * @author gaolong1 * * TODO 要更改此產生的類型注釋的模板,請轉至 * 視窗 - 喜好設定 - Java - 代碼樣式 - 代碼模板 */public class FileUpload extends HttpServlet {

 /**  * Destruction of the servlet. <br>  */ private String uploadPath = "D:\\addnetFile\\"; // 用於存放上傳檔案的目錄    private File tempPath =new File("D:\\addnetFile\\tmp\\"); // 用於存放臨時檔案的目錄 public void destroy() {  super.destroy(); // Just puts "destroy" string in log  // Put your code here }

 /**  * The doPost method of the servlet. <br>  *  * This method is called when a form has its tag value method equals to post.  *  * @param request the request send by the client to the server  * @param response the response send by the server to the client  * @throws ServletException if an error occurred  * @throws IOException if an 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 will be stored in memory        factory.setSizeThreshold(4096);        // the location for saving data that is larger than getSizeThreshold()        factory.setRepository(new File("d:\\File\\addnetFile\\temp"));

        ServletFileUpload upload = new ServletFileUpload(factory);        // maximum size before a FileUploadException will be thrown        upload.setSizeMax(1000000);        try{        List fileItems = upload.parseRequest(req);        // assume we know there are two files. The first file is a small        // text file, the second is unknown and is written to a file on        // the server        Iterator iter = fileItems.iterator();

//  正則匹配,過濾路徑取檔案名稱     String regExp=".+\\\\(.+)$";

//  過濾掉的檔案類型  String[] errorType={".exe",".com",".cgi",".asp"};     Pattern p = Pattern.compile(regExp);        while (iter.hasNext()) {         FileItem item = (FileItem)iter.next();         //忽略其他不是檔案域的所有表單資訊         if (!item.isFormField()) {             String name = item.getName();             long size = item.getSize();             if((name==null||name.equals("")) && size==0)                 continue;          Matcher m = p.matcher(name);         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{

//        儲存上傳的檔案到指定的目錄

//        在下文中上傳檔案至資料庫時,將對這裡改寫                     item.write(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);         }

//  儲存上傳的檔案到指定的目錄

//  在下文中上傳檔案至資料庫時,將對這裡改寫

    }

 /**  * Initialization of the servlet. <br>  *  * @throws ServletException if an error occure  */ public void init() throws ServletException {  // Put your code here }

}對應的請求檔案:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>index.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">

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

  </head>

  <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 action="./servlet/HelloWord" method="post">    <input type="submit"/>    </form>    <form name="uploadform" method="POST" action="./servlet/FileUpload" ENCTYPE="multipart/form-data">

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

        <tr><td width="100%" colspan="2">

                        檔案1:<input name="x" size="40" type="file">

        </td></tr>

        <tr><td width="100%" colspan="2">

                        檔案2:<input name="y" size="40" type="file">

        </td></tr>

        <tr><td width="100%" colspan="2">

                        檔案3:<input name="z" size="40" type="file">

        </td></tr>

        </table>

        <br/><br/>

        <table>

        <tr><td align="center"><input name="upload" type="submit" value="開始上傳"/></td></tr>

       </table>

</form>

  </body></html>註:該代碼由部分來自網上!


相關文章

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。