JSP中檔案的上傳於下載樣本

來源:互聯網
上載者:User

標籤:java   jsp   servlet   檔案上傳與下載   

一、檔案上傳的原理
    1、檔案上傳的前提:
        a、form表單的method必須是post
        b、form表單的enctype必須是multipart/form-data(決定了POST請求方式,請求本文的資料類型)
            注意:當表單的enctype是multipart/form-data,傳統的擷取請求參數的方法失效。
            
            請求本文:(MIME協議進行描述的,本文是多部分組成的)
            -----------------------------7dd32c39803b2
            Content-Disposition: form-data; name="username"

            wzhting
            -----------------------------7dd32c39803b2
            Content-Disposition: form-data; name="f1"; filename="C:\Documents and Settings\wzhting\妗岄潰\a.txt"
            Content-Type: text/plain

            aaaaaaaaaaaaaaaaaa
            -----------------------------7dd32c39803b2
            Content-Disposition: form-data; name="f2"; filename="C:\Documents and Settings\wzhting\妗岄潰\b.txt"
            Content-Type: text/plain

            bbbbbbbbbbbbbbbbbbb
            -----------------------------7dd32c39803b2--

            
        c、form中提供input的type是file類型的檔案上傳域
        
二、利用第三方組件實現檔案上傳
    1、commons-fileupload組件:
        jar:commons-fileupload.jar  commons-io.jar
    2、核心類或介面
        DiskFileItemFactory:設定環境
            public void setSizeThreshold(int?sizeThreshold) :設定緩衝區大小。預設是10Kb。
                    當上傳的檔案超出了緩衝區大小,fileupload組件將使用臨時檔案快取上傳檔案
            public void setRepository(java.io.File repository):設定臨時檔案的存放目錄。預設是系統的臨時檔案存放目錄。
                    
        ServletFileUpload:核心上傳類(主要作用:解析請求的本文內容)
            boolean isMultipartContent(HttpServletRequest?request):判斷使用者的表單的enctype是否是multipart/form-data類型的。
            List parseRequest(HttpServletRequest request):解析請求本文中的內容
            setFileSizeMax(4*1024*1024);//設定單個上傳檔案的大小
            upload.setSizeMax(6*1024*1024);//設定總檔案大小
        FileItem:代表表單中的一個輸入欄位。
            boolean isFormField():是否是普通欄位
            String getFieldName:擷取普通欄位的欄位名
            String getString():擷取普通欄位的值
            
            InputStream getInputStream():擷取上傳欄位的輸入資料流
            String getName():擷取上傳的檔案名稱
            
三、檔案上傳中要注意的9個問題
    1、如何保證伺服器的安全
        把儲存上傳檔案的目錄放到WEB-INF目錄中。
    2、中文亂碼問題
        2.1普通欄位的中文請求參數
            String value = FileItem.getString("UTF-8");
        2.2上傳的檔案名稱是中文
            解決辦法:request.setCharacterEncoding("UTF-8");
    3、重名檔案被覆蓋的問題
            System.currentMillions()+"_"+a.txt(樂觀)
            
            UUID+"_"+a.txt:保證檔案名稱唯一
    4、分目錄存放上傳的檔案
        方式一:當前日期建立一個檔案夾,當前上傳的檔案都放到此檔案夾中。
        方式二:利用檔案名稱的hash碼打散目錄來儲存。
            int hashCode = fileName.hashCode();
            
                1001 1010 1101 0010 1101 1100 1101 1010
hashCode&0xf;   0000 0000 0000 0000 0000 0000 0000 1111 &
                ---------------------------------------------
                0000 0000 0000 0000 0000 0000 0000 1010   取hashCode的後4位
                                                    0000~1111:整數0~15共16個
                
                1001 1010 1101 0010 1101 1100 1101 1010
(hashCode&0xf0)    0000 0000 0000 0000 0000 0000 1111 0000  &
                --------------------------------------------
                0000 0000 0000 0000 0000 0000 1101 0000  >>4
                --------------------------------------------
                0000 0000 0000 0000 0000 0000 0000 1101
                                                    0000~1111:整數0~15共16個
    5、限制使用者上傳的檔案類型
        通過判斷檔案的副檔名來限制是不可取的。
        通過判斷其Mime類型才靠譜。FileItem.getContentType();
    6、如何限制使用者上傳檔案的大小
        6.1單個檔案大小限制。超出了大小友好提示
            抓異常進行提示:org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException
        6.2總檔案大小限制。超出了大小友好提示
            抓異常進行提示:org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException
    7、臨時檔案的問題
        commons-fileupload組件不會刪除超出緩衝的臨時檔案。
        
        FileItem.delete()方法刪除臨時檔案。但一定要在關閉流之後。
    8、多個檔案上傳時,沒有上傳內容的問題
        if(fileName==null||"".equals(fileName.trim())){
            continue;
        }
    9、上傳進度檢測
        給ServletFileUpload註冊一個進度監聽器即可,把上傳進度傳遞給頁面去顯示
        //pBytesRead:當前以讀取到的位元組數
        //pContentLength:檔案的長度
        //pItems:第幾項
        public void update(long pBytesRead, long pContentLength,
                int pItems) {
            System.out.println("已讀取:"+pBytesRead+",檔案大小:"+pContentLength+",第幾項:"+pItems);

        }

四:檔案上傳樣本:

JSP代碼:

<form action="${pageContext.request.contextPath}/servlet/UploadServlet" method="post" enctype="multipart/form-data">    使用者名稱:<input type="text" name="username"/><br/>    檔案1:<input type="file" name="f1"/><br/>    檔案2:<input type="file" name="f2"/><br/>    <input type="submit" value="儲存"/>    </form>
servlet後台代碼:

public class UploadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");PrintWriter pout = response.getWriter();try {// 得到存放上傳檔案的真實路徑String storePath = getServletContext().getRealPath("/WEB-INF/files");// 設定環境DiskFileItemFactory factory = new DiskFileItemFactory();factory.setRepository(new File(getServletContext().getRealPath("/temp")));//設定臨時存放目錄// 判斷一下form是否是enctype=multipart/form-data類型的boolean isMultipart = ServletFileUpload.isMultipartContent(request);if (!isMultipart) {System.out.println("大傻鳥");return;}// ServletFileUpload核心類ServletFileUpload upload = new ServletFileUpload(factory);//upload.setProgressListener(new ProgressListener() {////pBytesRead:當前以讀取到的位元組數////pContentLength:檔案的長度////pItems:第幾項//public void update(long pBytesRead, long pContentLength,//int pItems) {//System.out.println("已讀取:"+pBytesRead+",檔案大小:"+pContentLength+",第幾項:"+pItems);//}////});upload.setFileSizeMax(4 * 1024 * 1024);// 設定單個上傳檔案的大小upload.setSizeMax(6 * 1024 * 1024);// 設定總檔案大小// 解析List<FileItem> items = upload.parseRequest(request);for (FileItem item : items) {if (item.isFormField()) {// 普通欄位String fieldName = item.getFieldName();String fieldValue = item.getString("UTF-8");System.out.println(fieldName + "=" + fieldValue);} else {// 得到MIME類型String mimeType = item.getContentType();// 只允許上傳圖片 if(mimeType.startsWith("image")){// 上傳欄位InputStream in = item.getInputStream();// 上傳的檔案名稱String fileName = item.getName();// C:\Documents andif(fileName==null||"".equals(fileName.trim())){continue;}// Settings\wzhting\妗岄潰\a.txt// a.txtfileName = fileName.substring(fileName.lastIndexOf("\\") + 1);// a.txtfileName = UUID.randomUUID() + "_" + fileName;System.out.println(request.getRemoteAddr()+"=============="+fileName);// 構建輸出資料流// 打散儲存目錄String newStorePath = makeStorePath(storePath, fileName);// 根據// /WEB-INF/files和檔案名稱,建立一個新的儲存路徑// /WEB-INF/files/1/12String storeFile = newStorePath + "\\" + fileName;// WEB-INF/files/1/2/sldfdslf.txtOutputStream out = new FileOutputStream(storeFile);byte b[] = new byte[1024];int len = -1;while ((len = in.read(b)) != -1) {out.write(b, 0, len);}out.close();in.close();item.delete();//刪除臨時檔案} }}} catch (org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e) {// 單個檔案超出大小時的異常pout.write("單個檔案大小不能超出4M");} catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) {// 總檔案超出大小時的異常pout.write("總檔案大小不能超出6M");} catch (Exception e) {e.printStackTrace();}}// 根據 /WEB-INF/files和檔案名稱,建立一個新的儲存路徑 /WEB-INF/files/1/12private String makeStorePath(String storePath, String fileName) {int hashCode = fileName.hashCode();int dir1 = hashCode & 0xf;// 0000~1111:整數0~15共16個int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整數0~15共16個String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12File file = new File(path);if (!file.exists())file.mkdirs();return path;}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

五:檔案下載

1.顯示上述儲存所有的照片資訊:

//顯示所有上傳的檔案,封裝到域對象中,交給jsp去顯示public class ShowAllFilesServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Map<String, String> map = new HashMap<String, String>();//key:UUID檔案名稱;value:老檔案名稱//得到隱藏檔的根目錄String storePath = getServletContext().getRealPath("/WEB-INF/files");//遞迴遍曆其中檔案File file = new File(storePath);treeWalk(file,map);//交給JSP去顯示:如何封裝資料.用Map封裝。key:UUID檔案名稱;value:老檔案名稱request.setAttribute("map", map);request.getRequestDispatcher("/listFiles.jsp").forward(request, response);}//遍曆/WEB-INF/files所有檔案,把檔案名稱放到map中private void treeWalk(File file, Map<String, String> map) {if(file.isFile()){//是檔案String uuidName = file.getName();//  UUID_a_a.txt//真實檔案名稱String oldName = uuidName.substring(uuidName.indexOf("_")+1);map.put(uuidName, oldName);}else{//是一個目錄File[] fs = file.listFiles();for(File f:fs){treeWalk(f,map);}}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
2.顯示所有檔案listFiles.jsp頁面中的內容:
<body>    <h1>本站有以下好圖片</h1>    <c:forEach items="${map}" var="me">    <c:url value="/servlet/DownloadServlet" var="url">    <c:param name="filename" value="${me.key}"></c:param>    </c:url>    ${me.value}  <a href="${url}">下載</a><br/>    </c:forEach>  </body>
3.檔案下載DownloadServlet:

public class DownloadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=UTF-8");OutputStream out = response.getOutputStream();String filename = request.getParameter("filename");//get請求方式filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8");//中文編碼//截取老檔案名稱String oldFileName = filename.split("_")[1];//得到儲存路徑String storePath = getServletContext().getRealPath("/WEB-INF/files");//得到檔案的全部路徑String filePath = makeStorePath(storePath, filename)+"\\"+filename;//判斷檔案是否存在File file = new File(filePath);if(!file.exists()){out.write("對比起!你要下載的檔案可能已經不存在了".getBytes("UTF-8"));return;}InputStream in = new FileInputStream(file);//通知用戶端以下載的方式開啟response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName, "UTF-8"));byte[] b = new byte[1024];int len = -1;while((len=in.read(b))!=-1){out.write(b, 0, len);}in.close();out.write("下載成功".getBytes("UTF-8"));}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}private String makeStorePath(String storePath, String fileName) {int hashCode = fileName.hashCode();int dir1 = hashCode & 0xf;// 0000~1111:整數0~15共16個int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整數0~15共16個String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12File file = new File(path);if (!file.exists())file.mkdirs();return path;}}


聯繫我們

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