commons-fileupload上传下载

 

  commons-fileupload依赖commons-io包。这里使用最新的commons-fileupload-1.2.1和commons-io-1.4。

   

    直接使用了,注意form表单必须添加enctype="multipart/form-data"属性。

    由于要使用HttpServletRequest request。写一个类方便action调用,这里把HttpServletRequest request作参数,接收action里的HttpServletRequest request。

   

List<Map<String, String>> vars = new ArrayList<Map<String, String>>();
  Map<String, String> map = new HashMap<String, String>();
  String uploadPath = request.getSession().getServletContext().getRealPath("/")+"//upload";
  String tempuploadPath = request.getSession().getServletContext().getRealPath("/")+"//upload//buffer//";
  File uploadFile = new File(uploadPath);
  if (!uploadFile.exists()) {
      uploadFile.mkdirs();
  }
  File tempPathFile = new File(tempuploadPath);
   if (!tempPathFile.exists()) {
      tempPathFile.mkdirs();
  }
   
     try{
         DiskFileItemFactory factory = new DiskFileItemFactory();
         factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
         factory.setRepository(tempPathFile);// 设置缓冲区目录
 
         ServletFileUpload upload = new ServletFileUpload(factory);
         upload.setSizeMax(20971520); // 设置最大文件尺寸
 
         List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
         Iterator<FileItem> i = items.iterator();
         while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            String fileName = fi.getName();
            if (fileName != null) {
                File fullFile = new File(fi.getName());
                File savedFile = new File(uploadPath, fullFile.getName());
                fi.write(savedFile);
                //
                map.put("FILENAME", fullFile.getName());
                map.put("FILEPATH", "upload//"+fullFile.getName());
                vars.add(map);
            }
         }
     } catch (Exception e) {
         e.printStackTrace();
     }   
     return vars;

    这里我采用文件上传到服务器某路径下,而数据库存储文件信息,包括文件名、文件相对路径等。添加一个返回值方便传递这些信息。这里采用request.getSession().getServletContext().getRealPath("/")取项目物理路径,具体上传操作参看API。

   使用超链接下载。由于map.put("FILEPATH", "upload//"+fullFile.getName())存储的项目的相对路径,传给href属性即可,<a href="" target="_blank"></a>。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值