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 }