1. 程式人生 > >把帶附件的form表單封裝到map裡

把帶附件的form表單封裝到map裡

直接上程式碼

private void DataformMap(ServletRequest request1, ServletResponse response1) throws ServletException, IOException, FileUploadException{
		HashMap PARA_MAP = new HashMap(); 
		 HttpServletRequest request = (HttpServletRequest)request1;
		 HttpServletResponse response = (HttpServletResponse)response1;
		
		String filePath = Constant.filePath;
		long MAX_SIZE = Integer.parseInt(this.getService().getSize())*1024*1024;// 設定上傳檔案最大為 3M
		if(filePath==null || "".equals(filePath)){
			Constant.filePath="c:\\filePath";
			filePath= "c:\\filePath";
		}
		if(MAX_SIZE==0){
			MAX_SIZE=3*1024*1024;
		}
		// 允許上傳的檔案格式的列表
		final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "txt",
				"doc", "docx", "mp3", "wma", "m4a", "rar" };
		response.setContentType("text/html");
		// 設定字元編碼為UTF-8, 這樣支援漢字顯示,而不是用預設的ISO8859
		response.setCharacterEncoding("UTF-8");
		// 例項化一個硬碟檔案工廠,用來配置上傳元件ServletFileUpload
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		dfif.setSizeThreshold(4096);// 設定上傳檔案時用於臨時存放檔案的記憶體大小,這裡是4K.多於的部分將臨時存在硬碟
		File upLoadFilePath = new File(filePath);
		if(!upLoadFilePath.exists()){upLoadFilePath.mkdir();}
		dfif.setRepository(upLoadFilePath);//  設定存放臨時檔案的目錄,web根目錄下的ImagesUploadTemp目錄
		PrintWriter out =null;
		List upLoadFileList = new ArrayList();
		// 用以上工廠例項化上傳元件
		ServletFileUpload sfu = new ServletFileUpload(dfif);
		// 設定最大上傳尺寸
		sfu.setSizeMax(MAX_SIZE);		
		// 從request得到 所有 上傳域的列表
		List fileList = null;
		fileList = sfu.parseRequest(request);		
		// 沒有檔案上傳
		if (fileList == null || fileList.size() == 0) {
			return;
		}
		// 得到所有上傳的檔案
		Iterator fileItr = fileList.iterator();
		// 迴圈處理所有檔案
		while (fileItr.hasNext()) {
			String path = null;
			FileItem fileItem = null;
			long size = 0;
			fileItem = (FileItem) fileItr.next();
			// sFormField(): 判斷FileItem類物件封裝的資料是一個普通文字表單欄位,還是一個檔案表單欄位,如果是普通表單欄位則返回true,否則返回false。因此,可以使用該方法判斷是否為普通表單域,還是檔案上傳表單域。
			if (fileItem!=null && fileItem.isFormField()) {
				String tmpParaName = fileItem.getFieldName();
				// UTF-8(之前設定的讀取中文檔名)轉成ISO-8859-1(http預設編碼)後轉成GBK(這是我專案的編碼)
				String nmsValue = new String ((StringUtil.changeNull(fileItem.getString())).getBytes("ISO-8859-1"),"GBK");
				// 轉義字元 防止xxs攻擊
				nmsValue = nmsValue.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
				nmsValue = nmsValue.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
				nmsValue = nmsValue.replaceAll("'", "&#39;");
				nmsValue = nmsValue.replaceAll("eval\\((.*)\\)", "");
				nmsValue = nmsValue.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
				nmsValue = nmsValue.replaceAll("alert%", "");
				PARA_MAP.put(tmpParaName, nmsValue);
				continue;
			}
			Map map = new HashMap();
			// 得到檔案的完整路徑
			path = fileItem.getName();
			// 得到檔案的大小
			size = fileItem.getSize();
			if ("".equals(path) || size == 0) {
				continue;
			}
			// 得到去除路徑的檔名
			String t_name = path.substring(path.lastIndexOf("\\") + 1);
			// 得到檔案的副檔名(無副檔名時將得到全名)
			String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
			// 拒絕接受規定檔案格式之外的檔案型別
			String bj=fileItem.getFieldName();
			//檔案型別暫不做限制
//			int allowFlag = 0;
//			int allowedExtCount = allowedExt.length;
//			for (; allowFlag < allowedExtCount; allowFlag++) {
//				if (allowedExt[allowFlag].equals(t_ext))
//					break;
//			}
//			if (allowFlag == allowedExtCount) {
//				RequestDispatcher rd=config.getServletContext().getRequestDispatcher(request.getContextPath()+"/error.html?error=0");
//				rd.forward(request,response);
//				return ;
//			}
			if("GIF".equalsIgnoreCase(t_ext) || "JPG".equalsIgnoreCase(t_ext) || "jpeg".equalsIgnoreCase(t_ext) || "bmp".equalsIgnoreCase(t_ext) ){
				map.put("ISPICTURE", "Y");
			}else{
				map.put("ISPICTURE", "N");
			}
			map.put("BJ", bj);
			map.put("FILETYPE", t_ext);
			map.put("FILENAME", t_name);
			map.put("fileItem", fileItem);
			upLoadFileList.add(map);
		}
	    String ip=request.getRemoteAddr();
	    PARA_MAP.put("IP", ip);
	    PARA_MAP.put(ConstVal.UPLOAD_FILE_LIST, upLoadFileList);
	    request.setAttribute("PARA_MAP", PARA_MAP);
	}

解釋1:有時候,為了讓中文字元適應某些特殊要求(如http header頭要求其內容必須為iso8859-1編碼),可能會通過將中文字元按照位元組方式來編碼的情況,如:
String s_iso88591 = new String(“中”.getBytes(“UTF-8”),“ISO8859-1”),這樣得到的s_iso8859-1字串實際是三個在ISO8859-1中的字元,在將這些字元傳遞到目的地後,目的地程式再通過相反的方式String s_utf8 = new String(s_iso88591.getBytes(“ISO8859-1”),“UTF-8”)來得到正確的中文漢字"中".這樣就既保證了遵守協議規定、也支援中文.