標籤:
1 //**檔案上傳** form表單提交必須指定Enctype 屬性指定將資料回傳到伺服器時瀏覽器使用的編碼類別型"multipart/form-data" 2 //1.建立磁碟檔案項目工廠 3 DiskFileItemFactory df=new DiskFileItemFactory(); 4 //2.設定上傳的記憶體緩衝區大小 4096=4KB 5 df.setSizeThreshold(4096); 6 //3.實列化Servlet檔案上傳對象 把‘磁碟檔案項目工廠‘放入構造中(把緩衝區大小放進去) 7 ServletFileUpload upload=new ServletFileUpload(df); 8 try { 9 //4.得到所有的上傳表單對象集合 返回List<FileItem> 相當於每一個表單元素都是一個FileItem10 List<FileItem> itemList=upload.parseRequest(request);11 //6.擷取檔案夾的絕對路徑12 String path=request.getSession().getServletContext().getRealPath("\\upload");13 14 //5.遍曆表單對象集合15 String ntid="";16 String ntitle="";17 String nauthor="";18 String nsummary="";19 String ncontent="";20 String file="";21 String name="";22 for(FileItem item:itemList){23 // System.out.println("InMemory:"+item.isInMemory());判斷FileItem對象是否是一個簡單的表單欄位24 25 //取出使用者提交內容26 if(item.isFormField()){//判斷 item是否是簡單的表單欄位27 if(item.getFieldName().equals("ntid")){28 ntid=item.getString("utf-8");29 }else if(item.getFieldName().equals("ntitle")){30 ntitle=item.getString("utf-8");31 }else if(item.getFieldName().equals("nauthor")){32 nauthor=item.getString("utf-8");33 }else if(item.getFieldName().equals("nsummary")){34 nsummary=item.getString("utf-8");35 }else if(item.getFieldName().equals("ncontent")){36 file=item.getString("utf-8");37 }38 }else{39 if(item.getFieldName().equals("file")){40 //得到使用者上傳檔案的路徑41 String fileName=item.getName();42 //截取最後檔案的名字43 int index=fileName.lastIndexOf("\\");44 name=fileName.substring(index+1);45 46 try {47 //把檔案寫入伺服器檔案夾48 item.write(new File(path,name));49 } catch (Exception e) {50 e.printStackTrace();51 }52 }53 }54 }55 } catch (FileUploadException e) {56 /* form表單中中沒有設定57 encType="multipart/form-data" method="post"58 會造成此異常(FileUploadBase$InvalidContentTypeException)59 */60 e.printStackTrace();61 }
需要:
commons-fileupload.jar commons-io.jar 兩個外掛程式
ServletFileUpload(Servlet檔案上傳)