檔案的上傳(照片上傳),檔案上傳照片上傳

來源:互聯網
上載者:User

檔案的上傳(照片上傳),檔案上傳照片上傳

1.檔案的上傳
   [1] 簡介
      > 將一個用戶端的本地的檔案發送到伺服器中儲存。
       > 上傳檔案是通過流的形式將檔案發送給伺服器。
 
   [2] 表單的設定
      > 向伺服器上傳一個檔案時,表單要使用post請求。
      > 表單的預設屬性enctype="application/x-www-form-urlencoded"
       - 這個屬性的意思是請求體中的內容將會使用URL編碼
      > 上傳檔案的表單enctype需要設定為 multipart/form-data
     - multipart/form-data表示的是表單是一個多組件的表單
     - 如果類型設定為它,則我們的每一個表單項都會作為一個單獨的組件發送給伺服器。
     - 多個組件之間使用類似 -----------------------------7df2d08c0892 分割符來分開
     > 當表單設定為multipart/form-data時,我們request.getParameter()將失效,我們不能再通過該方法擷取請求參數。

   [3] FileUpload
     > 我們一般情況下使用commons-fileupload-1.3.1.jar這個工具來解析多組件請求。
     > fileupload 依賴 commons-io 所以我們要是Filtupload需要同時匯入io包。
     > 核心類:
   DiskFileItemFactory
    - 工廠類,用於構建一個解析器執行個體。
    
   ServletFileUpload
    - 解析器類,通過該類執行個體來解析request中的請求資訊。
    
   FileItem
    - 工具會將我們請求中每一個組件,都封裝為一個FileItem對象,處理檔案上傳時,只需要調用該對象的方法
    - 方法:
     boolean isFormField()  --> 當前表單項是否是一個普通表單項,true是普通表單項, false是檔案表單項
     String getContentType() --> 返回的是檔案的類型,是MIME值
     String getFieldName()   --> 擷取表單項的name屬性值
     String getName()   --> 擷取上傳的檔案的名字
     long getSize()          --> 擷取檔案的大小
     String getString(String encoding) --> 擷取表單項的value屬性值,需要接受一個編碼作為參數。
     void write(File file)    --> 將表單項中的內容寫入到磁碟中
    
  > 使用步驟:
   1.擷取工廠類執行個體[DiskFileItemFactory]
   2.擷取解析器類執行個體[ServletFileUpload]
   3.解析request擷取FileItem[parseRequest()]

[4] 細節
  第一個問題
  > 部分瀏覽器會將檔案的完整路徑作為檔案名稱發送。
   C:\Users\lilichao\Desktop\day20\圖片\蒙娜麗莎.jpg
  > 像這類檔案名稱我們需要截取一下字串,只擷取名字這部分,而不需要擷取路徑部分的資訊。
   通過如下代碼對檔案名稱進行截取字串的操作:
    if(name.contains("\\")){
     //如果包含則截取字串
     name = name.substring(name.lastIndexOf("\\")+1);
    }
    
  第二個問題
  > 上傳的檔案有可能出現重名,後上傳的檔案會將先上傳的檔案覆蓋。
  > 解決:給檔案名稱加一個唯一的首碼。
    唯一標識_fennu.jpg
    UUID_fennu.jpg
  
  第三個問題
  > 有些情況需要限制上傳檔案的大小。
   - 設定單個檔案大小為50KB:
    fileUpload.setFileSizeMax(1024*50);
   - 設定完單個檔案大小限制以後,一旦上傳的檔案超過限制,則會拋出如下異常:
    FileSizeLimitExceededException
    所有可以對該異常進行捕獲,當出現該異常時則設定一個錯誤訊息。
   
   - 設定多個檔案的總大小為150KB
    fileUpload.setSizeMax(1024*150);
   - 當多個檔案的大小超出範圍時,會拋出如下異常
    SizeLimitExceededException
    
  第四個問題
   > 當使用者上傳一個空的檔案,依然會將檔案儲存到硬碟上。
   > 在儲存檔案應該先對檔案的大小進行判斷,如果size為0,則不處理。

 

下面是代碼實現部分:

  Servlet裡面的內容:

 1 package com.neuedu.servlet; 2  3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 import java.util.UUID; 7  8 import javax.servlet.ServletContext; 9 import javax.servlet.ServletException;10 import javax.servlet.annotation.WebServlet;11 import javax.servlet.http.HttpServlet;12 import javax.servlet.http.HttpServletRequest;13 import javax.servlet.http.HttpServletResponse;14 15 import org.apache.commons.fileupload.FileItem;16 import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;17 import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;18 import org.apache.commons.fileupload.FileUploadException;19 import org.apache.commons.fileupload.disk.DiskFileItemFactory;20 import org.apache.commons.fileupload.servlet.ServletFileUpload;21 22 23 24 25 26 @WebServlet("/FileUploadServlet")27 public class FileUploadServlet extends HttpServlet {28     private static final long serialVersionUID = 1L;29        30 31 32     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {33         //1.建立工廠類34         DiskFileItemFactory factory=new DiskFileItemFactory();35         //2.建立ServletFilUpload對象,通過這個對象完成上傳功能。36         ServletFileUpload fileUpload=new ServletFileUpload(factory);37 //        fileUpload.setFileSizeMax(1024*50);38         fileUpload.setSizeMax(1024*150);39         ServletContext servletContext = request.getServletContext();40         String realPath = servletContext.getRealPath("/upload");41         System.out.println(realPath);42         File file=new File(realPath);43         if(!file.exists())44         {45             file.mkdirs();46         }47         //2.用這個fileUpload對象解析request請求48         try {49             List<FileItem> fileList = fileUpload.parseRequest(request);50            for(FileItem item:fileList)51            {52               if(item.isFormField()){53                   //代表普通表單項54                   String name=item.getFieldName();55                   String value=item.getString("utf8");56                   System.out.println(name+":"+value);57                   58               }else {59                 //代表上傳的檔案60                   long size=item.getSize();61                   if(size==0){62                       continue;63                   }64                   String contentType = item.getContentType();65                   String name = item.getName();66                   if(name.contains("\\")){67                       name=name.substring(name.lastIndexOf("\\")+1);68                       69                   }70                   //uuid_name.jpg71                   String prefix = UUID.randomUUID().toString();72                   prefix=prefix.replace("-", "");73                   String fileName=prefix+"_"+name;74                   String fieldName=item.getFieldName();75                   System.out.println(size+":"+contentType+":------------"+name+":"+fieldName);76                   try {77                     item.write(new File(realPath+"\\"+fileName));78                 } catch (Exception e) {79                     // TODO Auto-generated catch block80                     e.printStackTrace();81                 }82                   83             }84            }85         } catch (FileSizeLimitExceededException e)86         {87             System.out.println("檔案大小不可以超過50k");88         }89         catch (SizeLimitExceededException e) {90             System.out.println("檔案大小不可以超過150K");91         }92         93         catch (FileUploadException e) {94             // TODO Auto-generated catch block95             e.printStackTrace();96         }97     }98 99 }
FileUploadServlet.java

JSP裡面的內容:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body>10 <form action="${pageContext.request.contextPath}/FileUploadServlet" method="post" enctype="multipart/form-data">11   使用者名稱:<input type="text" name="username"/><br/>12 <input type="file" name="photo"><br/>13 <input type="file" name="photo1"><br/>14 <input type="file" name="photo2"><br/>15 <input type="submit" value="提交">16 </form>17 </body>18 </html>
index.jsp

 

聯繫我們

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