cf3389b6a3cb382be6dca4634d5f16f259106b34.svn-base
9.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package com.thinkgem.jeesite.common.utils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* 文件上传工具类
*
* @author yangdc
* @date Apr 18, 2012
*
* <pre>
* </pre>
*/
public class UploadUtils {
/**
* 表单字段常量
*/
public static final String FORM_FIELDS = "form_fields";
/**
* 文件域常量
*/
public static final String FILE_FIELDS = "file_fields";
// 最大文件大小
private long maxSize = 1000000;
// 定义允许上传的文件扩展名
private Map<String, String> extMap = new HashMap<String, String>();
// 文件保存目录相对路径
private String basePath = "upload";
// 文件的目录名
private String dirName = "images";
// 上传临时路径
private static final String TEMP_PATH = "/temp";
private String tempPath = basePath + TEMP_PATH;
// 若不指定则文件名默认为 yyyyMMddHHmmss_xyz
private String fileName;
// 文件保存目录路径
private String savePath;
// 文件保存目录url
private String saveUrl;
// 文件最终的url包括文件名
private String fileUrl;
public UploadUtils() {
// 其中images,flashs,medias,files,对应文件夹名称,对应dirName
// key文件夹名称
// value该文件夹内可以上传文件的后缀名
extMap.put("images", "gif,jpg,jpeg,png,bmp");
extMap.put("flashs", "swf,flv");
extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("files", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
}
/**
* 文件上传
*
* @param request
* @return infos info[0] 验证文件域返回错误信息 info[1] 上传文件错误信息 info[2] savePath info[3] saveUrl info[4] fileUrl
*/
@SuppressWarnings("unchecked")
public String[] uploadFile(HttpServletRequest request) {
String[] infos = new String[5];
// 验证
infos[0] = this.validateFields(request);
// 初始化表单元素
Map<String, Object> fieldsMap = new HashMap<String, Object>();
if (infos[0].equals("true")) {
fieldsMap = this.initFields(request);
}
// 上传
List<FileItem> fiList = (List<FileItem>) fieldsMap.get(UploadUtils.FILE_FIELDS);
if (fiList != null) {
for (FileItem item : fiList) {
infos[1] = this.saveFile(item);
}
infos[2] = savePath;
infos[3] = saveUrl;
infos[4] = fileUrl;
}
return infos;
}
/**
* 上传验证,并初始化文件目录
*
* @param request
*/
private String validateFields(HttpServletRequest request) {
String errorInfo = "true";
// boolean errorFlag = true;
// 获取内容类型
String contentType = request.getContentType();
int contentLength = request.getContentLength();
// 文件保存目录路径
savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/";
// 文件保存目录URL
saveUrl = request.getContextPath() + "/" + basePath + "/";
File uploadDir = new File(savePath);
if (contentType == null || !contentType.startsWith("multipart")) {
// TODO
System.out.println("请求不包含multipart/form-data流");
errorInfo = "请求不包含multipart/form-data流";
} else if (maxSize < contentLength) {
// TODO
System.out.println("上传文件大小超出文件最大大小");
errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]";
} else if (!ServletFileUpload.isMultipartContent(request)) {
// TODO
errorInfo = "请选择文件";
} else if (!uploadDir.isDirectory()) {// 检查目录
// TODO
errorInfo = "上传目录[" + savePath + "]不存在";
} else if (!uploadDir.canWrite()) {
// TODO
errorInfo = "上传目录[" + savePath + "]没有写权限";
} else if (!extMap.containsKey(dirName)) {
// TODO
errorInfo = "目录名不正确";
} else {
// .../basePath/dirName/
// 创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
// .../basePath/dirName/yyyyMMdd/
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
// 获取上传临时路径
tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";
File file = new File(tempPath);
if (!file.exists()) {
file.mkdirs();
}
}
return errorInfo;
}
/**
* 处理上传内容
*
* @param request
* @param maxSize
* @return
*/
// @SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {
// 存储表单字段和非表单字段
Map<String, Object> map = new HashMap<String, Object>();
// 第一步:判断request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 阀值,超过这个值才会写到临时目录,否则在内存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上传限制
upload.setSizeMax(maxSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 第3步:处理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域对象
List<FileItem> list = new ArrayList<FileItem>();
// 表单字段
Map<String, String> fields = new HashMap<String, String>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 处理所有表单元素和文件域表单元素
if (item.isFormField()) { // 表单元素
String name = item.getFieldName();
String value = item.getString();
fields.put(name, value);
} else { // 文件域表单元素
list.add(item);
}
}
map.put(FORM_FIELDS, fields);
map.put(FILE_FIELDS, list);
}
}
return map;
}
/**
* 保存文件
*
* @param obj
* 要上传的文件域
* @param file
* @return
*/
private String saveFile(FileItem item) {
String error = "true";
String fileName = item.getName();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (item.getSize() > maxSize) { // 检查文件大小
// TODO
error = "上传文件大小超过限制";
} else if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {// 检查扩展名
error = "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。";
} else {
String newFileName;
if ("".equals(fileName.trim())) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
} else {
newFileName = fileName + "." + fileExt;
}
// .../basePath/dirName/yyyyMMdd/yyyyMMddHHmmss_xxx.xxx
fileUrl = saveUrl + newFileName;
try {
File uploadedFile = new File(savePath, newFileName);
item.write(uploadedFile);
/*
* FileOutputStream fos = new FileOutputStream(uploadFile); // 文件全在内存中 if (item.isInMemory()) { fos.write(item.get()); } else { InputStream is = item.getInputStream(); byte[] buffer =
* new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } is.close(); } fos.close(); item.delete();
*/
} catch (IOException e) {
e.printStackTrace();
System.out.println("上传失败了!!!");
} catch (Exception e) {
e.printStackTrace();
}
}
return error;
}
/** **********************get/set方法********************************* */
public String getSavePath() {
return savePath;
}
public String getSaveUrl() {
return saveUrl;
}
public long getMaxSize() {
return maxSize;
}
public void setMaxSize(long maxSize) {
this.maxSize = maxSize;
}
public Map<String, String> getExtMap() {
return extMap;
}
public void setExtMap(Map<String, String> extMap) {
this.extMap = extMap;
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
tempPath = basePath + TEMP_PATH;
}
public String getDirName() {
return dirName;
}
public void setDirName(String dirName) {
this.dirName = dirName;
}
public String getTempPath() {
return tempPath;
}
public void setTempPath(String tempPath) {
this.tempPath = tempPath;
}
public String getFileUrl() {
return fileUrl;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}