天天看點

servlet接收用戶端傳過來的圖檔,保留驗證

  1. public class Uploadfile1 extends HttpServlet {  
  2.     @Override  
  3.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  4.             throws ServletException, IOException {  
  5.         request.setCharacterEncoding("utf-8");  
  6.         //獲得磁盤檔案條目工廠。  
  7.         DiskFileItemFactory factory = new DiskFileItemFactory();  
  8.         //擷取檔案上傳需要儲存的路徑,upload檔案夾需存在。  
  9.         String path = request.getSession().getServletContext().getRealPath("/upload");  
  10.         //設定暫時存放檔案的存儲室,這個存儲室可以和最終存儲檔案的檔案夾不同。因為當檔案很大的話會占用過多記憶體是以設定存儲室。  
  11.         factory.setRepository(new File(path));  
  12.         //設定緩存的大小,當上傳檔案的容量超過緩存時,就放到暫時存儲室。  
  13.         factory.setSizeThreshold(1024*1024);  
  14.         //上傳處理工具類(高水準API上傳處理?)  
  15.         ServletFileUpload upload = new ServletFileUpload(factory);  
  16.         try{  
  17.             //調用 parseRequest(request)方法  獲得上傳檔案 FileItem 的集合list 可實作多檔案上傳。  
  18.             List<FileItem> list = (List<FileItem>)upload.parseRequest(request);  
  19.             for(FileItem item:list){  
  20.                 //擷取表單屬性名字。  
  21.                 String name = item.getFieldName();  
  22.                 //如果擷取的表單資訊是普通的文本資訊。即通過頁面表單形式傳遞來的字元串。  
  23.                 if(item.isFormField()){  
  24.                     //擷取使用者具體輸入的字元串,  
  25.                     String value = item.getString();  
  26.                     request.setAttribute(name, value);  
  27.                 }  
  28.                 //如果傳入的是非簡單字元串,而是圖檔,音頻,視訊等二進制檔案。  
  29.                 else{   
  30.                     //擷取路徑名  
  31.                     String value = item.getName();  
  32.                     //取到最後一個反斜杠。  
  33.                     int start = value.lastIndexOf("\\");  
  34.                     //截取上傳檔案的 字元串名字。+1是去掉反斜杠。  
  35.                     String filename = value.substring(start+1);  
  36.                     request.setAttribute(name, filename);  
  37.                     //收到寫到接收的檔案中。  
  38.                     OutputStream out = new FileOutputStream(new File(path,filename));  
  39.                     InputStream in = item.getInputStream();  
  40.                     int length = 0;  
  41.                     byte[] buf = new byte[1024];  
  42.                     System.out.println("擷取檔案總量的容量:"+ item.getSize());  
  43.                     while((length = in.read(buf))!=-1){  
  44.                         out.write(buf,0,length);  
  45.                     }  
  46.                     in.close();  
  47.                     out.close();  
  48.                 }  
  49.             }  
  50.         }catch(Exception e){  
  51.             e.printStackTrace();  
  52.         }  
  53.     }  
  54. }