Apache Commons fileUpload实现文件上传(一)

Apache Commons fileUpload实现文件上传(一)
2010年07月30日
  Apache的commons-fileupload.jar可方便的实现文件的上传功能,本文通过实例来介绍如何使用commons-fileupload.jar。
  @author:ZJ 07-2-22
  Blog: ' target='_blank'>http://zhangjunhd.blog.51cto.com/
  将Apache的commons-fileupload.jar放在应用程序的WEB-INF\lib下,即可使用。下面举例介绍如何使用它的文件上传功能。
  所使用的fileUpload版本为1.2,环境为Eclipse3.3+MyEclipse6.0。FileUpload 是基于 Commons IO的,所以在进入项目前先确定Commons IO的jar包(本文使用commons-io-1.3.2.jar)在WEB-INF\lib下。
  此文作示例工程可在文章最后的附件中下载。
  [b]示例[/b][b]1[/b]
  最简单的例子,通过ServletFileUpload静态类来解析Request,工厂类FileItemFactory会对mulipart类的表单中的所有字段进行处理,不只是file字段。getName()得到文件名,getString()得到表单数据内容,isFormField()可判断是否为普通的表单项。
  demo1.html
  
  
  
  File upload
  
  
  //必须是multipart的表单数据。
  
  Your name:
  
  File:
  
  
  
  
  
  
  demo1.jsp
  
  
  
  
  
  
   items = upload.parseRequest(request);
  Iterator itr = items.iterator();
  [b]while[/b] (itr.hasNext()) {
  FileItem item = (FileItem) itr.next();
  //检查当前项目是普通表单项目还是上传文件。
  [b]if[/b] (item.isFormField()) {//如果是普通表单项目,显示表单内容。
  String fieldName = item.getFieldName();
  [b]if[/b] (fieldName.equals("name")) //对应demo1.html中type="text" name="name"
  out.print("the field name is" + item.getString());//显示表单内容。
  out.print("
");
  } [b]else[/b] {//如果是上传文件,显示文件名。
  out.print("the upload file name is" + item.getName());
  out.print("
");
  }
  }
  } [b]else[/b] {
  out.print("the enctype must be multipart/form-data");
  }
  %>
  
  
  
  File upload
  
  
  
  
  结果:
  the field name isjeff
  the upload file name isD:\C语言考试样题\作业题.rar
  [b]示例[/b][b]2[/b]
  上传两个文件到指定的目录。
  demo2.html
  
  
  
  File upload
  
  
  
  File1:
  
  File2:
  
  
  
  
  
  
  demo2.jsp
  
  
  
  
  
  
  
   items = upload.parseRequest(request);//得到所有的文件
  Iterator itr = items.iterator();
  [b]while[/b](itr.hasNext()){//依次处理每个文件
  FileItem item=(FileItem)itr.next();
  String fileName=item.getName();//获得文件名,包括路径
  [b]if[/b](fileName!=[b]null[/b]){
  File fullFile=[b]new[/b] File(item.getName());
  File savedFile=[b]new[/b] File(uploadPath,fullFile.getName());
  item.write(savedFile);
  }
  }
  out.print("upload succeed");
  }
  [b]catch[/b](Exception e){
  e.printStackTrace();
  }
  }
  [b]else[/b]{
  out.println("the enctype must be multipart/form-data");
  }
  %>
  
  
  
  File upload
  
  
  
  
  结果:
  upload succeed
  此时,在"D:\temp"下可以看到你上传的两个文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值