JSP上傳檔案

來源:互聯網
上載者:User

標籤:c   code   ext   a   int   get   

用戶端

html form表單:

表單中enctype="multipart/form-data"的意思,是設定表單的MIME編碼。預設情況,這個編碼格式是application/x-www-form-urlencoded,不能用於檔案上傳;只有使用了multipart/form-data,才能完整的傳遞檔案資料,進行下面的操作.

 

HTML代碼

<form name="myform" action="MyJsp.jsp" method="post"

       enctype="multipart/form-data">

       File1:<br>

       <input type="file" name="myfile"><br>

       File2:<br>

       <input type="file" name="myfile"><br>

       <br>

       <input type="submit" name="submit" value="Commit">

</form>

 

伺服器端

Apache的commons-fileupload.jar可方便的實現檔案的上傳功能,本例子通過匯入這個commons-fileupload.jar。將Apache的commons-fileupload.jar放在應用程式的WEB-INF\lib下。

FileUpload 是基於 Commons IO的,所以在進入項目前先確定Commons IO的jar包在WEB-INF\lib下。

主要使用的如下:

FileItem-------DiskFileItemFactory-----ServletFileUpload

作用:

FileItem 用來封裝表單中的元素和資料。

ServletFileUpload 處理表單資料,將資料封裝到 FileItem 對象中。

DiskFileItemFactory FileItem 對象的工廠,可以設定緩衝區大小和存放臨時檔案目錄。

ServletFileUpload 處理上傳的檔案的資料,優先儲存在緩衝區,如果資料超過了緩衝區大小,則儲存到硬碟上,儲存在DiskFileItemFactory指定目錄下的臨時檔案。資料都接收完後,它再在從臨時檔案中將資料寫入到上傳檔案目錄下的指定檔案中,並刪除臨時檔案。

功能:

限制上傳檔案的大小

long MAXSIZE=1024*1024*3; 單位是byte,所以這裡指定的是3M

upload.setFileSizeMax(MAXSIZE);

設定臨時目錄

DiskFileItemFactory factory = new DiskFileItemFactory();

factory.setSizeThreshold(1024*1024); 設定了1M的緩衝區

factory.setRepository(new File("E:/temp")); 設定上傳檔案的臨時目錄

如果上傳的檔案小於1M,那麼檔案就在緩衝區中,然後寫入硬碟,不經過緩衝區。這樣也就不用硬碟的讀寫了,應該比較快。

定義伺服器能接受的檔案類型。

String[] allowTypes = new String[]{"jpg","jpeg"};

用數組定義可接受檔案的尾碼名,在讀取表單內容後,取得用戶端上傳檔案的全名,再截取尾碼名,取到最後一個.的下標,再拿到之後所有的字串:

String endName= fileName.substring(fileName.lastIndexOf(".")+1);

用數組遍曆,如果不在數組中有定義,那麼就不接受。

throw new RuntimeException("檔案類型["+endName+"],不支援");

 

最基本的代碼實現:
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try { 
List<FileItem> items = upload.parseRequest(request); //解析request請求
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) { //如果是表單域 ,就是非檔案上傳元素 
String name = item.getFieldName(); //擷取name屬性的值
String value = item.getString(); //擷取value屬性的值
} else { 
String fieldName = item.getFieldName(); //檔案域中name屬性的值
String fileName = item.getName(); //檔案的全路徑,絕對路徑名加檔案名稱 
String contentType = item.getContentType(); //檔案的類型
long size = item.getSize(); //檔案的大小,以位元組為單位 
File saveFile = new File("D:/test.jpg"); //定義一個file指向一個具體的檔案
item.write(saveFile); //把上傳的內容寫到一個檔案中
}

 

MyJsp.jsp代碼

File uploadPath = new File("D:\\temp");//上傳檔案目錄

      if (!uploadPath.exists()) {

         uploadPath.mkdirs();

      }

      // String uploadPath="D:\\temp";

      boolean isMultipart = ServletFileUpload.isMultipartContent(request);

      if (isMultipart == true) {

         try {

            FileItemFactory factory = newDiskFileItemFactory();

            ServletFileUpload upload = newServletFileUpload(factory);

            List<FileItem> items = upload.parseRequest(request);//得到所有的檔案

            Iterator<FileItem> itr = items.iterator();

            while (itr.hasNext()) {//依次處理每個檔案

                FileItem item = (FileItem) itr.next();

               String fileName = item.getName();//獲得檔案名稱,包括路徑

                if (fileName != null) {

                   File fullFile = newFile(item.getName());

                   File savedFile = newFile(uploadPath,

                         fullFile.getName());

                   item.write(savedFile);

                }

            }

            out.print("upload succeed");

         }catch(Exception e) {

            e.printStackTrace();

         }

      }else{

         out.println("the enctype must be multipart/form-data");

      }

 

聯繫我們

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

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

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.