1 package com.gootrip.util; 2 3 import java.io.File; 4 import java.util.*; 5 import org.apache.commons.fileupload.*; 6 import javax.servlet.http.HttpServletRequest; 7 import java.util.regex.Pattern; 8 import java.io.IOException; 9 import org.apache.commons.fileupload.servlet.ServletFileUpload; 10 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 11 import java.util.regex.Matcher; 12 13 14 /** 16 * 窗口 - 首選項 - Java - 代碼樣式 - 代碼模板 17 */ 18 public class FileUploadUtil { 19 20 //當上傳文件超過限制時設定的臨時文件位置,注意是絕對路徑 21 private String tempPath = null; 22 23 //文件上傳目標目錄,注意是絕對路徑 24 private String dstPath = null; 25 26 //新文件名稱,不設置時默認為原文件名 27 private String newFileName = null; 28 //獲取的上傳請求 29 private HttpServletRequest fileuploadReq = null; 30 31 //設置最多只允許在內存中存儲的數據,單位:字節,這個參數不要設置太大 32 private int sizeThreshold = 4096; 33 34 //設置允許用戶上傳文件大小,單位:字節 35 //共10M 36 private long sizeMax = 10485760; 37 38 //圖片文件序號 39 private int picSeqNo = 1; 40 41 private boolean isSmallPic = false; 42 43 public FileUploadUtil(){ 44 } 45 46 public FileUploadUtil(String tempPath, String destinationPath){ 47 this.tempPath = tempPath; 48 this.dstPath = destinationPath; 49 } 50 51 public FileUploadUtil(String tempPath, String destinationPath, HttpServletRequest fileuploadRequest){ 52 this.tempPath = tempPath; 53 this.dstPath = destinationPath; 54 this.fileuploadReq = fileuploadRequest; 55 } 56 57 /** 文件上載 58 * @return true —— success; false —— fail. 59 */ 60 public boolean Upload(){ 61 DiskFileItemFactory factory = new DiskFileItemFactory(); 62 63 try { 64 65 //如果沒有上傳目的目錄,則創建它 66 FileUtil.makeDirectory(dstPath+"/ddd"); 67 /*if (!FileUtil.makeDirectory(dstPath+"/ddd")) { 68 throw new IOException("Create destination Directory Error."); 69 }*/ 70 //如果沒有臨時目錄,則創建它 71 FileUtil.makeDirectory(tempPath+"/ddd"); 72 /*if (!FileUtil.makeDirectory(tempPath+"/ddd")) { 73 throw new IOException("Create Temp Directory Error."); 74 }*/ 75 76 //上傳項目只要足夠小,就應該保留在內存里。 77 //較大的項目應該被寫在硬盤的臨時文件上。 78 //非常大的上傳請求應該避免。 79 //限制項目在內存中所占的空間,限制最大的上傳請求,並且設定臨時文件的位置。 80 81 //設置最多只允許在內存中存儲的數據,單位:字節 82 factory.setSizeThreshold(sizeThreshold); 83 // the location for saving data that is larger than getSizeThreshold() 84 factory.setRepository(new File(tempPath)); 85 86 ServletFileUpload upload = new ServletFileUpload(factory); 87 //設置允許用戶上傳文件大小,單位:字節 88 upload.setSizeMax(sizeMax); 89 90 List fileItems = upload.parseRequest(fileuploadReq); 91 // assume we know there are two files. The first file is a small 92 // text file, the second is unknown and is written to a file on 93 // the server 94 Iterator iter = fileItems.iterator(); 95 96 // 正則匹配,過濾路徑取文件名 97 String regExp = ".+\\\\(.+)$"; 98 99 // 過濾掉的文件類型 100 String[] errorType = {".exe", ".com", ".cgi", ".asp", ".php", ".jsp"}; 101 Pattern p = Pattern.compile(regExp); 102 while (iter.hasNext()) { 103 System.out.println("++00++====="+newFileName); 104 FileItem item = (FileItem) iter.next(); 105 //忽略其他不是文件域的所有表單信息 106 if (!item.isFormField()) { 107 String name = item.getName(); 108 System.out.println("++++====="+name); 109 long size = item.getSize(); 110 //有多個文件域時,只上傳有文件的 111 if ((name == null || name.equals("")) && size == 0) 112 continue; 113 Matcher m = p.matcher(name); 114 boolean result = m.find(); 115 if (result) { 116 for (int temp = 0; temp < errorType.length; temp++) { 117 if (m.group(1).endsWith(errorType[temp])) { 118 throw new IOException(name + ": Wrong File Type"); 119 } 120 } 121 String ext = "."+FileUtil.getTypePart(name); 122 try { 123 //保存上傳的文件到指定的目錄 124 //在下文中上傳文件至數據庫時,將對這里改寫 125 //沒有指定新文件名時以原文件名來命名 126 if (newFileName == null || newFileName.trim().equals("")) 127 { 128 item.write(new File(dstPath +"/"+ m.group(1))); 129 } 130 else 131 { 132 String uploadfilename = ""; 133 if (isSmallPic) 134 { 135 uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+"_small"+ext; 136 } 137 else 138 { 139 uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+ext; 140 } 141 //生成所有未生成的目錄 142 System.out.println("++++====="+uploadfilename); 143 FileUtil.makeDirectory(uploadfilename); 144 //item.write(new File(dstPath +"/"+ newFileName)); 145 item.write(new File(uploadfilename)); 146 } 147 picSeqNo++; 148 //out.print(name + " " + size + "<br>"); 149 } catch (Exception e) { 150 //out.println(e); 151 throw new IOException(e.getMessage()); 152 } 153 } else { 154 throw new IOException("fail to upload"); 155 } 156 } 157 } 158 } catch (IOException e) { 159 System.out.println(e); 160 } catch (FileUploadException e) { 161 System.out.println(e); 162 } 163 return true; 164 } 165 166 /**從路徑中獲取單獨文件名 167 * @author 168 * 169 * TODO 要更改此生成的類型注釋的模板,請轉至 170 * 窗口 - 首選項 - Java - 代碼樣式 - 代碼模板 171 */ 172 public String GetFileName(String filepath) 173 { 174 String returnstr = "*.*"; 175 int length = filepath.trim().length(); 176 177 filepath = filepath.replace('\\', '/'); 178 if(length >0) 179 { 180 int i = filepath.lastIndexOf("/"); 181 if (i >= 0) 182 { 183 filepath = filepath.substring(i + 1); 184 returnstr = filepath; 185 } 186 } 187 return returnstr; 188 } 189 /** 190 * 設置臨時存貯目錄 191 */ 192 public void setTmpPath(String tmppath) 193 { 194 this.tempPath = tmppath; 195 } 196 /** 197 * 設置目標目錄 198 */ 199 public void setDstPath(String dstpath) { 200 this.dstPath = dstpath; 201 } 202 /** 203 * 設置最大上傳文件字節數,不設置時默認10M 204 */ 205 public void setFileMaxSize(long maxsize) { 206 this.sizeMax = maxsize; 207 } 208 /** 209 * 設置Http 請求參數,通過這個能數來獲取文件信息 210 */ 211 public void setHttpReq(HttpServletRequest httpreq) { 212 this.fileuploadReq = httpreq; 213 } 214 /** 215 * 設置Http 請求參數,通過這個能數來獲取文件信息 216 */ 217 public void setNewFileName(String filename) { 218 this.newFileName = filename; 219 } 220 221 /** 222 * 設置此上傳文件是否是縮略圖文件,這個參數主要用於縮略圖命名 223 */ 224 public void setIsSmalPic(boolean isSmallPic) { 225 this.isSmallPic = isSmallPic; 226 } 227 228 /** 229 * 設置Http 請求參數,通過這個能數來獲取文件信息 230 */ 231 public void setPicSeqNo(int seqNo) { 232 this.picSeqNo = seqNo; 233 } 234 235 236 }