/** * Destruction of the servlet. <br> */ private String uploadPath = "D:\\addnetFile\\"; // 用於存放上傳檔案的目錄 private File tempPath =new File("D:\\addnetFile\\tmp\\"); // 用於存放臨時檔案的目錄 public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here }
/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ res.setContentType( "text/html; charset=GB2312"); PrintWriter out=res.getWriter(); System.out.println(req.getContentLength()); System.out.println(req.getContentType()); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() factory.setRepository(new File("d:\\File\\addnetFile\\temp"));
ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown upload.setSizeMax(1000000); try{ List fileItems = upload.parseRequest(req); // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server Iterator iter = fileItems.iterator();
// 正則匹配,過濾路徑取檔案名稱 String regExp=".+\\\\(.+)$";
// 過濾掉的檔案類型 String[] errorType={".exe",".com",".cgi",".asp"}; Pattern p = Pattern.compile(regExp); while (iter.hasNext()) { FileItem item = (FileItem)iter.next(); //忽略其他不是檔案域的所有表單資訊 if (!item.isFormField()) { String name = item.getName(); long size = item.getSize(); if((name==null||name.equals("")) && size==0) continue; Matcher m = p.matcher(name); boolean result = m.find(); if (result){ for (int temp=0;temp<errorType.length;temp++){ if (m.group(1).endsWith(errorType[temp])){ throw new IOException(name+": wrong type"); } } try{
/** * Initialization of the servlet. <br> * * @throws ServletException if an error occure */ public void init() throws ServletException { // Put your code here }
}對應的請求檔案:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>index.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page">