檔案上傳,

來源:互聯網
上載者:User

檔案上傳,
一、檔案上傳概述 1 檔案上傳的作用例如網路硬碟!就是用來上傳下載檔案的。在招聘網上填寫一個完整的簡曆還需要上傳照片等。2 檔案上傳對頁面的要求上傳檔案的要求比較多,需要記一下:

  • 必須使用表單,而不能是超連結;
  • 表單的method必須是POST,而不能是GET;
  • 表單的enctype必須是multipart/form-data;
  • 在表單中添加file表單欄位,即<input type=”file“ name=”xxx” />
1 <form action="${pageContext.request.contextPath }/FileUploadServlet" method="post" enctype="multipart/form-data">2 使用者名稱:<input type="text" name="username"/><br/>3 檔案1:<input type="file" name="file1"/><br/>4 檔案2:<input type="file" name="file2"/><br/>5 <input type="submit" value="提交"/>6 </form>
3 檔案上傳對Servlet的要求
  • request.getParameter(String)方法擷取指定的表單欄位字元內容,但檔案上傳表單已經不在是字元內容,而是位元組內容,所以失效。
  • ServletInputStream request.getInputStream():包含整個請求體。

4 多組件表單的體

  ①每隔出多個組件,即一個表單項一個組件。

  ②一個組件中位元組包含要求標頭和空行,以及請求體

  ③普通表單項:

  • 1個頭:Content-Disposition:包含name=“xxxx”,即表單項名稱
  • 體就是表單項的值

  ④檔案表單項:

  • Content-Disposition: 包含name=“xx”,即表單項名稱,還有一個filename=“xx”,表示上傳檔案的名稱
  • Content-Type:它是上傳檔案的MINE類型,例如:image/pjpeg,表示上傳的圖片,圖中jpg副檔名的圖片。
  • 體就是上傳檔案的內容
Request Headersview parsedPOST /form1.jsp HTTP/1.1Host: localhost:8080Connection: keep-aliveContent-Length: 479756Cache-Control: max-age=0Origin: http://localhost:8080Upgrade-Insecure-Requests: 1Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8Wne2EqQO2Ps7E8mUser-Agent: ****Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Referer: http://localhost:8080/form1.jspAccept-Encoding: gzip, deflate, brAccept-Language: zh,en-US;q=0.8,en;q=0.6,zh-CN;q=0.4Cookie: Idea-e96526d7=db12919d-58f1-479a-b0f7-3104911c767b; JSESSIONID=9DEFDF98FE8715CB5707772F874D8C82Request Payload------WebKitFormBoundary8Wne2EqQO2Ps7E8mContent-Disposition: form-data; name="username"zhangsan------WebKitFormBoundary8Wne2EqQO2Ps7E8mContent-Disposition: form-data; name="picture"; filename="2.jpg"Content-Type: image/jpeg------WebKitFormBoundary8Wne2EqQO2Ps7E8m--
5 commons-fileupload  fileupload是由apache的commons組件提供的上傳組件。它最主要的工作就是幫我們解析request.getInputStream()。fileupload組件需要的JAR包有:
  • commons-fileupload.jar,核心包;
  • commons-io.jar,依賴包。

二、fileupload簡單應用

1、fileupload的核心類有:DiskFileItemFactory、ServletFileUpload、FileItem。  使用fileupload組件的步驟如下:

①建立工廠類DiskFileItemFactory對象:DiskFileItemFactory factory = new DiskFileItemFactory()

②使用工廠建立解析器對象:ServletFileUpload fileUpload = new ServletFileUpload(factory)

③使用解析器來解析request對象:List<FileItem> list = fileUpload.parseRequest(request)

2、FileItem

  一個FileItem對象對應一個表單項(表單欄位)。  一個表單中存在檔案欄位和普通欄位,可以使用FileItem類的isFormField()方法來判斷表單欄位是否為普通欄位,如果不是普通欄位,那麼就是檔案欄位了。
  • boolean isFormField():判斷當前表單欄位是否為普通文字欄位,如果返回false,說明是檔案欄位;
  • String getFieldName():擷取欄位名稱,例如:<input type=”text” name=”username”/>,返回的是username;
  • String getName():擷取檔案欄位的檔案名稱;
  • String getString(String charset):擷取欄位的內容,如果是檔案欄位,那麼擷取的是檔案內容,當然上傳的檔案必須是文字檔;
  • String getContentType():擷取上傳的檔案的類型,例如:text/plain。
  • long getSize():返回上傳檔案的位元組數;
  • InputStream getInputStream():擷取上傳檔案對應的輸入資料流;
  • void write(File):把上傳的檔案儲存到指定檔案中。

3、樣本:

 1 package servlet; 2  3 import org.apache.commons.fileupload.FileItem; 4 import org.apache.commons.fileupload.FileUploadException; 5 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 6 import org.apache.commons.fileupload.servlet.ServletFileUpload; 7  8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet;10 import javax.servlet.http.HttpServlet;11 import javax.servlet.http.HttpServletRequest;12 import javax.servlet.http.HttpServletResponse;13 import java.io.File;14 import java.io.IOException;15 import java.util.List;16 17 @WebServlet(name = "Upload2Servlet",urlPatterns = "/Upload2Servlet")18 public class Upload2Servlet extends HttpServlet {19     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {20         request.setCharacterEncoding("utf-8");21         response.setContentType("text/html;charset=utf-8");22         /*23         * 1、得到工廠24         * 2、通過工廠建立解析器25         * 3、解析request,得到FileItem集合26         * 4、遍曆FileItem集合,調用其API完成檔案的儲存27         * */28         DiskFileItemFactory factory = new DiskFileItemFactory();29         ServletFileUpload sfu = new ServletFileUpload(factory);30         try {31             List<FileItem> fileItems = sfu.parseRequest(request);32             FileItem fileItem1 = fileItems.get(0);33             FileItem fileItem2 = fileItems.get(1);34 35             System.out.println("普通表單項示範:"+fileItem1.get()+36                     "="+fileItem1.toString());37             System.out.println("檔案表單示範:");38             System.out.println("Content-Type:" + fileItem2.getContentType());39             System.out.println("size:"+fileItem2.getSize());40             System.out.println("filename:"+fileItem2.getName());41             //儲存檔案42             File destFile = new File("/Users/Shared/picture.jpg");43             try {44                 fileItem2.write(destFile);45             } catch (Exception e) {46                 throw new RuntimeException(e);47             }48         } catch (FileUploadException e) {49             throw new RuntimeException(e);50         }51     }52 }
 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <html> 4 <head> 5     <title>Title</title> 6 </head> 7 <body> 8 <h1>上傳2</h1> 9 <form action="<c:url value='/Upload2Servlet'/>" method="post" enctype="multipart/form-data">10     使用者名稱:<input type="text" name="username"/><br/>11     照片: <input type="file" name="picture" /><br/>12     <input type="submit" value="上傳">13 </form>14 </body>15 </html>

三、上傳的細節

1. 檔案必須儲存到WEB-INF下!
* 目的是不讓瀏覽器直接存取到!
* 把檔案儲存到WEB-INF目錄下!
2. 檔案名稱相關問題
 * 有的瀏覽器上傳的檔案名稱是絕對路徑,這需要切割!C:\files\baibing.jpg
String filename = fi2.getName();
int index = filename.lastIndexOf("\\");
if(index != -1) {
filename = filename.substring(index+1);
}
* 檔案名稱亂碼或者普通表單項亂碼:request.setCharacterEncoding("utf-8");因為fileupload內部會調用request.getCharacterEncoding();
> request.setCharacterEncoding("utf-8");//優先順序低
> servletFileUpload.setHeaderEncoding("utf-8");//優先順序高
* 檔案同名問題:我們需要為每個檔案添加名稱首碼,這個首碼要保證不能重複。uuid
> filename = CommonUtils.uuid() + "_" + filename;
3. 目錄打散
* 不能在一個目錄下存放之多檔案。
> 首字元打散:使用檔案的首字母做為目錄名稱,例如:abc.txt,那麼我們把檔案儲存到a目錄下。如果a目錄這時不存在,那麼建立之。
> 時間打散:使用當前日期做為目錄。
> 雜湊打散:
* 通過檔案名稱得到int值,即調用hashCode()
* 它int值轉換成16進位0~9, A~F
* 擷取16進位的前兩位用來組建目錄,目錄為二層!例如:1B2C3D4E5F,/1/B/儲存檔案。
4. 上傳檔案的大小限制
* 單個檔案大小限制
> sfu.setFileSizeMax(100*1024):限制單個檔案大小為100KB
> 上面的方法調用,必須在解析開始之前調用!
> 如果上傳的檔案超出限制,在parseRequest()方法執行時,會拋出異常!FileUploadBase.FileSizeLimitExceededException
* 整個請求所有資料大小限制
> sfu.setSizeMax(1024 * 1024);//限制整個表單大小為1M
> 這個方法也是必須在parseRequest()方法之前調用
> 如果上傳的檔案超出限制,在parseRequest()方法執行時,會拋出異常!FileUploadBase.SizeLimitExceededException
5. 緩衝大小與臨時目錄
* 緩衝大小:超出多大,才向硬碟儲存!預設為10KB
* 臨時目錄:向硬碟的什麼目錄儲存
設定緩衝大小與臨時目錄:new DiskFileItemFactory(20*1024, new File("F:/temp"))
 

四、目錄打散、上傳的大小限制、緩衝大小與臨時目錄樣本: 

 1 package servlet; 2  3 import cn.itcast.commons.CommonUtils; 4 import org.apache.commons.fileupload.FileItem; 5 import org.apache.commons.fileupload.FileUploadBase; 6 import org.apache.commons.fileupload.FileUploadException; 7 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 8 import org.apache.commons.fileupload.servlet.ServletFileUpload; 9 10 import javax.servlet.ServletException;11 import javax.servlet.annotation.WebServlet;12 import javax.servlet.http.HttpServlet;13 import javax.servlet.http.HttpServletRequest;14 import javax.servlet.http.HttpServletResponse;15 import java.io.File;16 import java.io.IOException;17 import java.util.List;18 @WebServlet(name = "Upload3Servlet",urlPatterns = "/Upload3Servlet")19 public class Upload3Servlet extends HttpServlet {20     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {21         request.setCharacterEncoding("utf-8");22         response.setContentType("text/html;charset=utf-8");23 24         //工廠25         DiskFileItemFactory factory = new DiskFileItemFactory(20*1024,new File("/Users/Shared/temp"));26         //解析器27         ServletFileUpload sfu = new ServletFileUpload(factory);28 29 //        sfu.setFileSizeMax(100*1024);//限制單個檔案大小為100KB30 //        sfu.setSizeMax(100*1024);//限制整個表單大小為100KB31         //解析,得到List32         try {33             List<FileItem> list = sfu.parseRequest(request);34             FileItem fi = list.get(1);35 36             //1、得到檔案儲存的路徑37             String root = this.getServletContext().getRealPath("/WEB-INF/files");38             /*39             * 2、產生二層目錄40             * 得到檔案名稱41             * 得到hashCode42             * 轉寄成16進位43             * 擷取前兩個字元用來組建目錄44             * */45             String filename = fi.getName();//擷取上傳檔案名稱46             //處理檔案名稱的絕對路徑問題47             int index = filename.lastIndexOf("//");48             if (index != 1) {49                 filename = filename.substring(index+1);50             }51             //給檔案名稱添加UUID首碼,處理檔案同名問題52             String savename = CommonUtils.uuid()+"_"+filename;53             //1、得到hashCode54             int hCode = filename.hashCode();55             String hex = Integer.toHexString(hCode);56             //2、擷取hex的前兩個字母,與root串連在一起,產生一個完整的路徑57             File dirFile = new File(root,hex.charAt(0)+"/"+hex.charAt(1));58             //3、建立目錄鏈59             dirFile.mkdirs();60             //4、建立目錄檔案61             File destFile = new File(dirFile,savename);62             //5、儲存63             fi.write(destFile);64         } catch (FileUploadException e) {65             if(e instanceof FileUploadBase.FileSizeLimitExceededException) {66                 request.setAttribute("msg", "您上傳的檔案超出了100KB!");67                 request.getRequestDispatcher("/form3.jsp").forward(request, response);68             }69         } catch (Exception e) {70             e.printStackTrace();71         }72     }73 }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.