朋友使用common-fileupload框架开发文件上传功能时获取不到上传的文件数据,代码如下:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="pro.jsp" method="post" accept-charset="utf-8" enctype="multipart/form-data">
文件:<input type="file" name="file" /><br/>
参数:<input type="text" name="text" /><br/>
<input type="submit" name="submit" value="提交">
</form>
</body>
</html>
pro.jsp:
<%@ page language="java" import="java.util.*,java.io.*"
pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置上传工厂的限制
factory.setSizeThreshold(1024*1024*20);
factory.setRepository(new File(request.getRealPath("/")));
//创建一个上传文件的ServletFileUpload对象
ServletFileUpload upload=new ServletFileUpload(factory);
//设置最大的上传限制
upload.setSizeMax(1024*1024*20);
//处理HTTP请求,items是所有的表单项
List items=upload.parseRequest(request);
for(Iterator it=items.iterator();it.hasNext();){
FileItem item=(FileItem)it.next();
if(item.isFormField()){
String name=item.getFieldName();
String value=item.getString("utf-8");
out.println("key:value-->"+name+"="+value+"<br/>");
}
else{
//取得文件域的表单域名
String fieldName=item.getFieldName();
//取得文件名
String fileName=item.getName();
String contentType=item.getContentType();
//以当前时间生成上传文件的文件名
FileOutputStream fos=new FileOutputStream(request.getRealPath("/")+
System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf(".",fileName.length())));
if(item.isInMemory())
fos.write(item.get());
else{
InputStream is = item.getInputStream();
byte[] buffer=new byte[1024];
int len;
//读取上传文件的内容,并将其写入服务器的文件中
while((len=is.read(buffer))>0)
fos.write(buffer,0,len);
is.close();
fos.close();
}
}
}
%>
将其代码拷贝到本地测试,竟然上传成功,刚想和朋友开玩笑说是RP问题时,突然想到在struts2的核心拦截器org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter中会对request进一步的封装以便struts2对request进行更多的操作(其实调用的是org.apache.struts2.dispatcher.Dispatcher类的wrapRequest方法),然后便将struts2加入到代码中测试,得到的结果和朋友的一样。具体是struts2对request进行了什么样的操作导致了这个问题笔者尚未研究,暂且在这里记录一下吧~~
但如果既用common-fileupload进行文件上传,又使用struts2进行开发,有没有办法解决以上的问题呢?当然有,只要在struts2的配置文件中加入一个名为“struts.action.excludePattern”的变量,并将其值设置为“/pro.jsp”即可。如果有多个路径,使用逗号分割。
版权所有,转载请标明出处:http://blogwarning.iteye.com/blog/1384953