<form action="upload/testupload" enctype="multipart/form-data"
method="post">
<input type="file" name="file" multiple="multiple" /><input
type="submit" value="submit" />
</form>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
public final void upload() throws Exception {
final StringBuilder result = new StringBuilder()
final DiskFileItemFactory dfif = new DiskFileItemFactory()
final ServletFileUpload sfu = new ServletFileUpload(dfif)
// 对requests对象进行解析,并把表单中的每一个输入项包装成一个fileItem对象,并返回一个保存了所有FileItem的list集合.
final List<FileItem> fileItems = sfu.parseRequest(getRequest())
final Iterator<FileItem> iter = fileItems.iterator()
final String path = "F:/resources/Test/"
FileItem item = null
String name = null
int error = 0
int length = 0
// 设置内存缓冲区的大小,默认值为10K,如果文件大于10K,将使用临时文件缓存上传文件.
dfif.setSizeThreshold(10 * 1024)
dfif.setRepository(new File(path))
// 设置上传文件总量的最大值 500M
sfu.setSizeMax(500 * 1024 * 1024)
// 设置上传文件最大值 其中文件大小只要有一个超过 (100M) ,1024KB==1M 所有文件将不能上传
sfu.setFileSizeMax(100 * 1024 * 1024)
result.append("{\"files\":[")
while (iter.hasNext()) {
System.out.println(iter.hasNext())
item = iter.next()
if (!item.isFormField()) {
length++
name = item.getName()
name = System.currentTimeMillis() + name.substring(name.lastIndexOf("."), name.length())
result.append("\"").append(name).append("\"").append(!iter.hasNext() ? "" : ",")
item.write(new File(path + name))
}
}
result.append("],\"error\":").append(error).append(",\"success\":").append(length - error)
.append(",\"path\":\"").append(path).append("\"}")
renderJson(result.toString())
}