81,092
社区成员
发帖
与我相关
我的任务
分享
<%@ page contentType="text/html; charset=utf-8" language="java"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>文件上传</title>
</head>
<body>
<table border="0" cellpadding="2px" cellspacing="0px">
<tr><td>
<form name="UploadForm" enctype="multipart/form-data" method="post" action="../../UpFileServlet.do">
<input type="file" id="ff" class="T_B_L_R" />
<input type="submit" value="上传" class="T_B_L_R" />
</form>
</td></tr>
<div id="more" />
<tr>
<td valign="middle" align="center">
</td>
</tr>
</table>
</body>
</html>
long size=20*1024*1024;
SmartUpload sup = new SmartUpload();
try{
sup.initialize(this.getServletConfig(), request, response);
System.out.println("begin");
sup.setMaxFileSize(size); //最大允许上传20M
sup.setAllowedFilesList("txt");
sup.upload();
System.out.println("size:"+sup.getSize());
System.out.println("count:"+sup.save("/upload/normal/"));
}
catch(Exception e){
e.printStackTrace();
}
final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
response.setContentType("text/html");
// 设置字符编码为UTF-8, 这样支持汉字显示
response.setCharacterEncoding("UTF-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setRepository(new File(this.getServletContext().getRealPath("") + "/upload/temp/"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
// 从request得到 所有 上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (Exception e) {
e.printStackTrace();
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String prefix = String.valueOf(now);
// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
String u_name = request.getRealPath("") + "/upload/normal/"
+ prefix + "." + t_ext;
try {
// 保存文件
fileItem.write(new File(u_name));
out.println("文件上传成功. 已保存为: " + prefix + "." + t_ext
+ " 文件大小: " + size + "字节<p />");
} catch (Exception e) {
e.printStackTrace();
}
}
}