日期:2014-05-17 浏览次数:20745 次
import java.io.File;
import java.util.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@SuppressWarnings({ "deprecation", "unchecked" })
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final long MAX_SIZE = 10*1024*1024; //设置上传文件最大为10M
final String[] allowedExt = new String[]{"jpg","jpeg","gif","txt","doc","docx","mp3","wma","w4a","bmp","JPG"};
resp.setContentType("text/html");
//设置字符编码为UTF-8,这样支持汉字显示
resp.setCharacterEncoding("UTF-8");
//实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
//设置上传文件时用于临时存放文件的内存大小,这里是4K,多余部分将临时存在硬盘
dfif.setSizeThreshold(4096);
//设置存放临时文件的目录,web根目录下的ImagesUploadTemp
dfif.setRepository(new File(req.getRealPath("/")+"ImagesUploadTemp"));
//用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
//设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = resp.getWriter();
//从req得到所有上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(req);
}catch(FileUploadException e) { //处理文件尺寸过大异常
if(e instanceof SizeLimitExceededException) {
out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节</p>");
out.println("<a href=\"\\chap11\\fileupload.jsp\" target=\"_top\">返回</a>");
return;
}
//没有文件上传
if(fileList == null || fileList.size() == 0) {
out.println("请选择上传文件1</p>");
out.println("<a href=\"\\chap11\\fileupload.jsp\" target=\"_top\">返回</a>");
return;
}
//得到所有上传的文件
Iterator fileltr = fileList.iterator();
//循环处理所有文件
while(fileltr.hasNext()) {
FileItem fileitem = null;
String path = null;
long size = 0;
//得到当前文件
fileitem = (FileItem)fileltr.next();