本帖最后由 mark4956123 于 2012-11-22 14:56:40 编辑
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
final long MAX_SIZE = 300 * 1024 * 1024;// 设置上传文件最大值
//允许上传文件格式的列表
final String[] allowedExt = new String[]{"jpg", "jpeg", "gif", "txt", "doc", "mp3", "wma", "m4a", "rar", "zip"};
response.setContentType("text/html");
// 设置字符编码为UTF-8, 统一编码,处理出现乱码问题
response.setCharacterEncoding("UTF-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setRepository(new File(request.getRealPath("/")+"ImagesUploadTemp"));
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
//设置最大上传大小
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
//从request得到所有上传域的列表
List fileList = null;
try{
fileList = sfu.parseRequest(request);
}catch(FileUploadException e){
// 处理文件尺寸过大异常
if(e instanceof SizeLimitExceededException){
out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p/>");
out.println("<a href=\"#\" >返回</a>");
return;
}
e.printStackTrace();
}
//没有文件上传
if(fileList == null || fileList.size() == 0){
out.println("请选择上传文件<p/>");
out.println("<a href=\"#\" >返回</a>");
return;
}
//得到所有上传的文件
Iterator fileItr = fileList.iterator();
//循环处理所有文件
while(fileItr.hasNext()){
FileItem fileItem = null;
String path = null;