当前位置: 代码迷 >> J2EE >> commons fileupload
  详细解决方案

commons fileupload

热度:117   发布时间:2016-04-22 00:19:08.0
在线等 commons fileupload

在获取 list items = sfu.parseRequest(request);  获取为空 获取不到东西

Action
public class UpFileAction extends DispatchAction {

public ActionForward upFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException
{
if(ServletFileUpload.isMultipartContent(request)) {
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getContextPath()+"/tmp"));
//内存最大占用
factory.setSizeThreshold(4096);
ServletFileUpload sfu = new ServletFileUpload(factory);
//单个文件最大值byte
sfu.setFileSizeMax(1024*1024*1024);
//所有上传文件的总和最大值byte
sfu.setSizeMax(1024*1024*1024*2);
List items = null;
try {
items = sfu.parseRequest(request);
} catch (SizeLimitExceededException e) {
System.out.println("size limit exception!");
} catch(Exception e) {
e.printStackTrace();
}

Iterator iter = items==null?null:items.iterator();
while(iter != null && iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//简单的表单域
if(item.isFormField()) {
System.out.print("form field:");
System.out.print(item.getFieldName() + "  ");
System.out.print(item.getString());

//文件域
else if(!item.isFormField()) {
System.out.println("client name:" + item.getName());
String fileName = item.getName();
BufferedInputStream in = new BufferedInputStream(item.getInputStream());
//文件存储在工程的upload目录下
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(request.getContextPath()+"/upload/" + fileName)));
Streams.copy(in, out, true);
}
}
} else {
System.out.println("enctype error!");
}
return mapping.findForward("index");
}



  jsp  页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" contect="text/html;charset=utf-8">
</head>
<body>
<form action="${pageContext.request.contextPath }/fileInfo.do?op=upFile" method="post"
enctype="multipart/form-data">
<!-- file对应的input必须有name属性,否则不能上传 -->
<input type="file" name="file"/>
<input type="submit" value="submit" />
</form>
</body>
</html>



------解决方案--------------------
不要用dispatch而是直接execute试试看
------解决方案--------------------
因为你只上传的一个文件 所以为空, 你DEBUG 他的长度也为空, 你可以在JSP页面中添加个
username:<input type="text" name="username"></input>


这样子就好了!
------解决方案--------------------
  相关解决方案