標籤:load throw 資料流 單元素 image field com doctype 迴圈
一、檔案上傳
- 檔案上傳,即伺服器端得到並處理使用者上傳的檔案,這個檔案存放在request裡,也就是需要對request進行處理。
1.1 編寫html檔案
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body> <form action="servlet/upload" method="post" enctype= "multipart/form-data"> 檔案描述:<input type="text" name="desc" /><br/> <input type="file" name="file" /><br/> <input type="submit" value="上傳" /> </form></body></html>
解析:enctype= "multipart/form-data" 是實現檔案上傳必不可缺少的屬性,但是加了此屬性之後,就不能以 request.getParameter(arg0); 來擷取表單值,只能通過getFieldName()擷取表單名,getString()擷取表單值。
1.2 編寫servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");fileUpload(request);} /*
*檔案上傳
*/
public void fileUpload(HttpServletRequest request) { //磁碟檔案工廠類DiskFileItemFactory主要是設定臨時檔案目錄DiskFileItemFactory diff=new DiskFileItemFactory();diff.setSizeThreshold(10*1024*1024); //設定上傳檔案大小的臨界值,大於這個值就先存在臨時目錄,然後在上傳到伺服器。小於這個值直接上傳到伺服器。10Mdiff.setRepository(new File(this.getServletContext().getRealPath("tmp"))); //設定臨時檔案目錄 //臨時檔案設定好之後,就可以處理上傳的檔案了。ServletFileUpload upload=new ServletFileUpload(diff); //檔案上傳對象upload按照檔案工廠diff的配置
/*接下來可以對request進行解析了,*request的資料分為普通表單資料和檔案,需要區別對待處理。* 對request解析出來的是List<FileItem>類型的,一個表單值就是一個對象。 */List<FileItem> items=null;try {items=upload.parseRequest(request);//對request進行解析,解析出來的是List<FileItem>類型的for(FileItem item:items){ //對錶單裡所有資料進行迴圈,然後對錶單資料和檔案資料區分處理if(item.isFormField()){//如果為表單資料if("desc".equals(item.getFieldName())){ //如果表單元素的元素名是desc,System.out.println("檔案的描述為:"+item.getString("UTF-8")); //item.getString("UTF-8")解決亂碼問題}}else{//否則為檔案資料String path=this.getServletContext().getRealPath("upload"); //擷取存放上傳檔案的檔案夾真實路徑(即在硬碟上的路徑,而不是在項目中的相對路徑)OutputStream os=new FileOutputStream(new File(path+"/"+item.getName()));//使用者上傳檔案的路徑為path檔案夾裡,名字是item.getName()即上傳時候的檔案名稱
if(item.isInMemory()){ // 如果檔案是直接存放在記憶體的,即小於臨時檔案的臨界值,小於10M,可以直接將使用者上傳的檔案直接拷貝到upload檔案裡。os.write(item.get());//item.get()得到使用者上傳的檔案的資料流}else{ //如果上傳檔案大小大於臨界值,這個檔案會現在臨時檔案夾tmp裡,然後再上傳到upload檔案夾裡。IOUtils.copy(item.getInputStream(), os); //直接將使用者檔案的資料流拷貝到輸出資料流即可}os.close();}}} catch (Exception e) {e.printStackTrace();}}
右擊項目名,選擇“properties”,
開啟圖中的path:“C:\Users\Administrator\workspace” ,選擇第一個檔案夾
找到這個檔案夾
找到項目名,點擊進去:
即可找到upload或者tmp檔案夾。
(七)利用apache組件進行檔案上傳下載