標籤:lis blog parse new etc mfa 必須 trace ring
- 提供form表單,提交方式method必須為post
- form表單的enctype(告知伺服器請求本文的MIME類型)必須是:multipart/form-data
- 提供 <input type="file"> 上傳的輸入欄位
- fileupload是由apache的commons組件提供的上傳組件。它最主要的工作就是幫我們解析request.getInputStream()。
- 匯入相關的jar
l commons-fileupload.jar,核心包
l commons-io.jar,依賴包
- DiskFileFactory
- ServletFileUpload
- FileItem
1 import java.io.File; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 6 import javax.servlet.http.HttpServletRequest; 7 8 import org.apache.commons.fileupload.FileItem; 9 import org.apache.commons.fileupload.disk.DiskFileItemFactory;10 import org.apache.commons.fileupload.servlet.ServletFileUpload;11 import org.apache.commons.io.FilenameUtils;12 13 public class MyFileUpload {14 15 public static Map<String,String[]> getFileUpload(HttpServletRequest request){16 //1擷取表單資料17 //*1.1建立工廠類DiskFileItemFactory對象18 DiskFileItemFactory factory = new DiskFileItemFactory();19 //*1.2使用工廠建立解析對象20 ServletFileUpload fileUpload = new ServletFileUpload(factory);21 //*1.3使用解析器來解析request對象22 //用於封裝普通表單項的資料23 Map<String, String[]> map = new HashMap<String,String[]>();24 25 try {26 List<FileItem> list = fileUpload.parseRequest(request);27 for (FileItem item : list) {28 if(item.isFormField()){ 29 //如果裡面封裝的是普通資料30 String name = item.getFieldName(); //欄位名31 String value = item.getString("UTF-8"); //欄位的值32 map.put(name,new String[]{value});33 }else{ 34 //裡面是檔案表單資料35 String filename = item.getName();//上傳的檔案名稱36 String extension = FilenameUtils.getExtension(filename);//檔案的副檔名37 //上傳的檔案的副檔名不能是jsp和exe38 if(!(extension.equals("jsp")||extension.equals("exe"))){39 //建立目錄40 File storeDir = new File(request.getServletContext().getRealPath("/WEB-INF/upload"));41 if(!storeDir.exists()){42 storeDir.mkdirs(); //目錄不存在就建立目錄43 }44 //處理檔案名稱45 if(filename !=null&&(!"".equals(filename))){46 filename = FilenameUtils.getName(filename);47 }else{48 continue;49 }50 51 //目錄打散52 String childDir = makeChildDir(storeDir,filename);53 filename = childDir+File.separator+filename;54 //System.out.println(storeDir); 55 try {56 item.write(new File(storeDir,filename));//!!!!!!!儲存路徑57 item.delete();58 } catch (Exception e) {59 e.printStackTrace();60 }61 map.put(item.getFieldName(), new String[]{filename});62 }63 }64 }65 } catch (Exception e) {66 e.printStackTrace();67 }68 return map;69 }70 private static String makeChildDir(File storeDir, String filename) {71 int hashcode = filename.hashCode(); //返回字串轉換的32位的hashcode碼72 String code = Integer.toHexString(hashcode);//把hashcode轉換為16進位的字元73 74 String childDir = code.charAt(0)+File.separator+code.charAt(1);// a/b75 //建立指定目錄76 File file = new File(storeDir,childDir); //根據storeDir的路徑建立一個新的childDir路徑77 if(!file.exists()){78 file.mkdirs();79 }80 return childDir;81 }82 83 }
檔案的上傳