最近项目需要用到上传文件,找了个fileupload组件,写了几个类,记录如下:
1.上传操作配置类
1public class UpConfig {
2 private long max_size=10*1024*1024; //最大上传文件大小,默认10M
3 private HttpServletRequest request; //请求体对象
4 private String targetDir; //下载目录,相对路径
5 private String baseDir=""; //应用目录
6 private String tmpDir="/tmp"; //临时文件目录,默认为根目录下的tmp目录
7 private int memBufSize=1024*10; //缓冲内存区大小,默认10k
8 private List fileTypeList=new ArrayList(); //允许 上传文件类型
9 private List fileList=new ArrayList(); //返回文件列表
10 private ProgressListener listener=null; //上传进度对象,默认生成UpProgress类实例
11
12 public UpConfig(HttpServletRequest request){
13 this.request=request;
14 addFileType("txt");
15 addFileType("rar");
16 }
17
18 public long getMaxSize() {
19 return max_size;
20 }
21 public void setMaxSize(long size) {
22 this.max_size = size;
23 }
24 public HttpServletRequest getRequest() {
25 return request;
26 }
27
28 public String getTargetDir() {
29 return getBase_dir()+targetDir;
30 }
31 public void setTargetDir(String dir) {
32 this.targetDir =dir;
33 }
34
35 public String getBase_dir() {
36 if("".equals(baseDir)&&request!=null){
37 baseDir=request.getSession().getServletContext().getRealPath("/");
38 }
39 return baseDir;
40 }
41
42 public String getTmpDir() {
43 return getBase_dir()+tmpDir;
44 }
45
46 public int getMemBufSize() {
47 return memBufSize;
48 }
49 public void setMemBufSize(int size) {
50 this.memBufSize = size;
51 }
52 public List getFileTypeList() {
53 return fileTypeList;
54 }
55 public void addFileType(String t) {
56 if(!fileTypeList.contains(t)){
57 fileTypeList.add(t);
58 }
59 }
60 public void put(String f){
61 if(!fileList.contains(f.trim())){
62 fileList.add(f);
63 }
64 }
65 /** *//**
66 * 获取上传文件路径列表
67 * @return
68 */
69 public List getFileList(){
70 return fileList;
71 }
72
73 public ProgressListener getListener() {
74 if(listener==null){
75 listener=new UpProgress(request);
76 }
77 return listener;
78 }
79
80 public void setListener(ProgressListener listener) {
81 this.listener = listener;
82 }
83}
2.上传进度类,实际只是实现了一个接口的方法而已
1public class UpProgress implements ProgressListener {
2 private HttpSession session=null;
3
4 public UpProgress(HttpServletRequest request){
5 if(request!=null) session=request.getSession();
6 }
7
8 public void update(long bytesRead, long totalSize, int itemIndex) {
9 if(session!=null){
10// System.err.print(System.currentTimeMillis()+"更新上传进度\r\n");
11 Map uploadMap=null;
12 Object o=session.getAttribute("UploadMap");
13 if(o==null){
14 uploadMap=new HashMap();
15 }else{
16 uploadMap=(Map)o;
17 }
18 uploadMap.put("bytesRead",Long.toString(bytesRead)); //已上传大小
19 uploadMap.put("totalSize", Long.toString(totalSize)); //文件总大小
20 uploadMap.put("itemIndex",Integer.toString(itemIndex)); //当前上传文件序号
21 session.setAttribute("UploadMap",uploadMap);
22 }
23 }
24
25}
3.上传操作类
1public class Upload {
2
3 /** *//**
4 * 处理上传文件
5 * @param request
6 * @param config 上传配置类,具体属性参考UpConfig类
7 * @throws HsException
8 */
9 public static void dealUploadFile(UpConfig config) throws HsException{
10 DiskFileItemFactory factory=new DiskFileItemFactory();
11 factory.setSizeThreshold(config.getMemBufSize());
12 File tmpFile=new File(config.getTmpDir());
13 if(!tmpFile.exists()) tmpFile.mkdir();
14 factory.setRepository(tmpFile);
15 ServletFileUpload fup=new ServletFileUpload(factory);
16 fup.setSizeMax(config.getMaxSize());
17 fup.setProgressListener(config.getListener());
18 try{
19 List filelist=fup.parseRequest(config.getRequest());
20 Iterator it=filelist.iterator();
21 while(it.hasNext()){
22 FileItem fileItem=(FileItem)it.next();
23 if(fileItem==null||fileItem.isFormField()) continue;
24 String fileName=fileItem.getName().substring(fileItem.getName().lastIndexOf("\\")+1);
25 String ext=fileName.substring(fileName.lastIndexOf(".")+1);
26 if(!config.getFileTypeList().contains(ext)){
27 throw new HsException("0001","不允许上传"+ext+"格式的文件");
28 }
29 String t_dir=config.getTargetDir();
30 File f=new File(t_dir);
31 if(!f.exists()) f.mkdir();
32 String f_name=t_dir+"/"+fileName.substring(0,fileName.lastIndexOf("."))+"_"+
33 System.currentTimeMillis()+"."+ext;
34 fileItem.write(new File(f_name));
35 config.put(f_name);
36 }
37 }catch(Exception e){
38 e.printStackTrace();
39 if(e instanceof SizeLimitExceededException){
40 throw new HsException("0001","文件大小超出范围!");
41 }else{
42 throw new HsException("0001",e.toString());
43 }
44 }
45 }
46}
调用upload类之后可以通过ajax动态获取session中的上传进度。现在使用还是比较粗浅,以后有时间好好研究一下。