使用apache.commons.fileupload组件来进行文件上传

1. 从www.apache.org的common项目下搞到commons-fileupload.jar 和commons-io.jar,导入项目。

2. jsp页面中,form的属性设置要求为:
<form action="uploadServlet" method="post" enctype="multipart/form-data">
其中,post和multipart/form-data要求必须指定。

3. 创建处理请求的Servlet:

<span style="font-size: medium;">DiskFileItemFactory factory = new DiskFileItemFactory();
// 获得项目根路径
String path = request.getRealPath("/");
// 设置缓存路径
factory.setRepository(new File(path));
// 设置文件缓存到硬盘的大小临界值
factory.setSizeThreshold(1024 * 1024);

ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
try {
// 指定解析request
List<FileItem> list = (List<FileItem>)
servletFileUpload.parseRequest(request);
for (FileItem item : list)
{
// 非文件的表单字段
if (item.isFormField() == true){
String filedName = item.getFieldName(); // 获得字段名
String value = item.getString("UTF-8"); // 获得字段值
System.out.println("fieldName=" + filedName);
System.out.println("value=" + value);

}else{ //文件表单字段
String fieldName = item.getFieldName(); // 获得字段名
String value = item.getName(); // 获得文件名
System.out.println("fieldName=" + fieldName);
System.out.println("file path=" + value);
// 处理浏览器兼容问题处理
int index = value.lastIndexOf("\\");
String fileName = value.substring(index + 1);

item.write(new File(path, fileName));
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}</span>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值