1. 程式人生 > >fileupload檔案上傳

fileupload檔案上傳

PrintWriter pw =request.getWriter();
 try{
 DiskFileItemFactory diskFactory = new DiskFileItemFactory();
 // threshold 極限、臨界值,即硬碟快取 1M
  diskFactory.setSizeThreshold(4 * 1024);
   // repository 貯藏室,即臨時檔案目錄
   diskFactory.setRepository(new File(tempPath));

  ServletFileUpload upload = new ServletFileUpload(diskFactory);
  // 設定允許上傳的最大檔案大小 4M 
  upload.setSizeMax(4 * 1024 * 1024);
  // 解析HTTP請求訊息頭
 List fileItems = upload.parseRequest(req);
 Iterator iter = fileItems.iterator();
  while(iter.hasNext())
 { 
   FileItem item = (FileItem)iter.next();
   if(item.isFormField())
  {
   System.out.println("處理表單內容 ...");
   processFormField(item, pw);
  }else{
   System.out.println("處理上傳的檔案 ...");
    processUploadFile(item, pw);
  }
 }
pw.close();

}catch(Exception e){
 System.out.println("使用 fileupload 包時發生異常 ...");
  e.printStackTrace();
 }
 }


// 處理表單內容
private void processFormField(FileItem item, PrintWriter pw)
throws Exception
 {
  String name = item.getFieldName();
 String value = item.getString();
 pw.println(name + " : " + value + "\r\n");
}

// 處理上傳的檔案
 private void processUploadFile(FileItem item, PrintWriter pw)
 throws Exception 
{
 // 此時的檔名包含了完整的路徑,得注意加工一下 
 String filename = item.getName();  
  System.out.println("完整的檔名:" + filename);
 int index = filename.lastIndexOf("\\");
 filename = filename.substring(index + 1, filename.length());

 long fileSize = item.getSize();

  if("".equals(filename) && fileSize == 0) 
  {          
          System.out.println("檔名為空 ...");
   return;
  } 

 File uploadFile = new File(filePath + "/" + filename);
 item.write(uploadFile);
 pw.println(filename + " 檔案儲存完畢 ...");
 pw.println("檔案大小為 :" + fileSize + "\r\n");
 }