List items = upload.parseRequest(request),items为空

大卷小渣渣 2012-07-11 05:01:57
jsp的form里面这样写的:
<html:form method="post" action="/t04_report/t04_report_list.do" enctype="multipart/form-data">
Action里面这样写的:
private ActionForward performImportReports(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存缓冲区,超过后写入临时文件
factory.setSizeThreshold(10240000);
// 设置临时文件存储位置
String base = this.getServletContext().getRealPath("/")+"files";
System.out.println("--------base----------------->"+base);
File file = new File(base);
System.out.println("------------>"+file.exists());
if(!file.exists()){
file.mkdirs();
}
factory.setRepository(file);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置单个文件的最大上传值
upload.setFileSizeMax(10002400000l);
// 设置整个request的最大值
upload.setSizeMax(10002400000l);
upload.setHeaderEncoding("gb2312");
try {
List<?> items = upload.parseRequest(request);
System.out.println("itemsSize--------------->"+items.size());//值为0,纠结啊。。。
FileItem item = null;
String fileName = null;
for (int i = 0 ;i < items.size(); i++){
item = (FileItem) items.get(i);
fileName = base + File.separator + item.getName();
System.out.println("------------------>"+item.getFieldName());
// 保存文件
System.out.println("--------fileName-------->"+fileName);

if (!item.isFormField() && item.getName().length() > 0) {
item.write(new File(fileName));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

List items = upload.parseRequest(request),items为空,不知道怎么办了,求大哥们帮忙解决啊!
...全文
2036 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
lion_teng 2015-03-24
  • 打赏
  • 举报
回复
求救,没用框架的咋办
lion_teng 2015-03-24
  • 打赏
  • 举报
回复
我什么框架都没有用呀,怎么改Web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
jack__ming 2015-01-27
  • 打赏
  • 举报
回复
那struts1呢?
加州小马哥 2014-12-17
  • 打赏
  • 举报
回复
大家好,遇到这个问题的朋友们。 如果用的是springmvc的架构,那么注释掉掉springmvc文件上传的配置即可; 如果用struts2的朋友们,在一楼的基础上,将constant name= "struts.multipart.handler" 改为constant name= "struts.multipart.parserr"即可。
lhz4023 2014-10-09
  • 打赏
  • 举报
回复
就是没有把common-io.jar包导进去
降龙108掌 2014-03-16
  • 打赏
  • 举报
回复
为啥我那样加进去了,提示No result defined for action 去掉<bean type= "org.apache.struts2.dispatcher.multipart.MultiPartRequest" name= "myRequestParser" class= "com.icf.common.base.actions.RequestParseWrapper" scope= "default" optional= "true " /> <constant name= "struts.multipart.handler" value= "myRequestParser" /> 的配置,程序能进入action,只是没能获取上传的文件
lsw0419 2014-02-17
  • 打赏
  • 举报
回复
十分感谢,终于解决了
泡面王 2013-08-06
  • 打赏
  • 举报
回复
引用 1 楼 dinglongfei 的回复:
在status2 的配置文件里加上 <bean type= "org.apache.struts2.dispatcher.multipart.MultiPartRequest" name= "myRequestParser" class= "com.icf.common.base.actions.RequestParseWrapper" scope= "default" optional= "true " /> <constant name= "struts.multipart.handler" value= "myRequestParser" /> class public class RequestParseWrapper extends JakartaMultiPartRequest { publicvoid parse(HttpServletRequest servletRequest, String saveDir)throws IOException{ } } 这样就可以得到request里的item
一楼的方法有用,感谢,搞了半天了,终于出来了。谢了。
liqifei009 2013-03-15
  • 打赏
  • 举报
回复
一楼大侠的办法很好,解决了我纠结以旧的问题,在这里谢了
  • 打赏
  • 举报
回复
public void uploadFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
request.setCharacterEncoding("GBK");
HttpSession session=request.getSession();
session.setAttribute("progressBar",0); //定义指定上传进度的Session变量
String error = "";
int maxSize=50*1024*1024; //单个上传文件大小的上限
DiskFileItemFactory factory = new DiskFileItemFactory(); //基于磁盘文件项目创建一个工厂对象
ServletFileUpload upload = new ServletFileUpload(factory); //创建一个新的文件上传对象
try {
List items = upload.parseRequest(request);// 解析上传请求
Iterator itr = items.iterator();// 枚举方法
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next(); //获取FileItem对象
if (!item.isFormField()) {// 判断是否为文件域
if (item.getName() != null && !item.getName().equals("")) {// 判断是否选择了文件
long upFileSize=item.getSize(); //上传文件的大小
String fileName=item.getName(); //获取文件名
//System.out.println("上传文件的大小:" + item.getSize());
if(upFileSize>maxSize){
error="您上传的文件太大,请选择不超过50M的文件";
break;
}
// 此时文件暂存在服务器的内存中
File tempFile = new File(fileName);// 构造临时对象
String uploadPath = this.getServletContext().getRealPath("/upload");
File file = new File(uploadPath,tempFile.getName()); // 获取根目录对应的真实物理路径
InputStream is=item.getInputStream();
int buffer=1024; //定义缓冲区的大小
int length=0;
byte[] b=new byte[buffer];
double percent=0;
FileOutputStream fos=new FileOutputStream(file);
while((length=is.read(b))!=-1){
percent+=length/(double)upFileSize*100D; //计算上传文件的百分比
fos.write(b,0,length); //向文件输出流写读取的数据
session.setAttribute("progressBar",Math.round(percent)); //将上传百分比保存到Session中
}
fos.close();
Thread.sleep(1000); //线程休眠1秒
} else {
error="没有选择上传文件!";
}
}
}
} catch (Exception e) {
e.printStackTrace();
error = "上传文件出现错误:" + e.getMessage();
}
if (!"".equals(error)) {
request.setAttribute("error", error);
request.getRequestDispatcher("error.jsp").forward(request, response);
}else {
request.setAttribute("result", "文件上传成功!");
request.getRequestDispatcher("upFile_deal.jsp").forward(request, response);
}
看看这个例子吧
  • 打赏
  • 举报
回复
enctype="multipart/form-data"去掉就可以了
ithoney 2012-09-26
  • 打赏
  • 举报
回复
同样错误,纠结中~
dinglongfei 2012-08-29
  • 打赏
  • 举报
回复
在status2 的配置文件里加上
<bean type= "org.apache.struts2.dispatcher.multipart.MultiPartRequest"
name= "myRequestParser" class= "com.icf.common.base.actions.RequestParseWrapper"
scope= "default" optional= "true " />
<constant name= "struts.multipart.handler" value= "myRequestParser" />
class
public class RequestParseWrapper extends JakartaMultiPartRequest {

publicvoid parse(HttpServletRequest servletRequest, String saveDir)throws IOException{
}
}
这样就可以得到request里的item
将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下。 此文作示例工程可在文章最后的附件中下载。 示例1 最简单的例子,通过ServletFileUpload静态类来解析Request,工厂类FileItemFactory会对mulipart类的表单中的所有字段进行处理,不只是file字段。getName()得到文件名,getString()得到表单数据内容,isFormField()可判断是否为普通的表单项。 demo1.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> //必须是multipart的表单数据。 <form name="myform" action="demo1.jsp" method="post" enctype="multipart/form-data"> Your name:
<input type="text" name="name" size="15"><br> File:
<input type="file" name="myfile"><br>
<input type="submit" name="submit" value="Commit"> </form> </body> </html> demo1.jsp <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <% boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。 if (isMultipart == true) { FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。 ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); //检查当前项目是普通表单项目还是上传文件。 if (item.isFormField()) {//如果是普通表单项目,显示表单内容。 String fieldName = item.getFieldName(); if (fieldName.equals("name")) //对应demo1.html中type="text" name="name" out.print("the field name is" + item.getString());//显示表单内容。 out.print("
"); } else {//如果是上传文件,显示文件名。 out.print("the upload file name is" + item.getName()); out.print("
"); } } } else { out.print("the enctype must be multipart/form-data"); } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> </body> </html> 结果: the field name isjeff the upload file name isD:\C语言考试样题\作业题.rar 示例2 上传两个文件到指定的目录。 demo2.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> <form name="myform" action="demo2.jsp" method="post" enctype="multipart/form-data"> File1:
<input type="file" name="myfile"><br> File2:
<input type="file" name="myfile"><br>
<input type="submit" name="submit" value="Commit"> </form> </body> </html> demo2.jsp <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*"%> <%String uploadPath="D:\\\\temp"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart==true){ try{ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request);//得到所有的文件 Iterator itr = items.iterator(); while(itr.hasNext()){//依次处理每个文件 FileItem item=(FileItem)itr.next(); String fileName=item.getName();//获得文件名,包括路径 if(fileName!=null){ File fullFile=new File(item.getName()); File savedFile=new File(uploadPath,fullFile.getName()); item.write(savedFile); } } out.print("upload succeed"); } catch(Exception e){ e.printStackTrace(); } } else{ out.println("the enctype must be multipart/form-data"); } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> </body> </html> 结果: upload succeed 此时,在"D:\temp"下可以看到你上传的两个文件。 示例3 上传一个文件到指定的目录,并限定文件大小。 demo3.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> <form name="myform" action="demo3.jsp" method="post" enctype="multipart/form-data"> File:
<input type="file" name="myfile"><br>
<input type="submit" name="submit" value="Commit"> </form> </body> </html> demo3.jsp <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*"%> <% File uploadPath = new File("D:\\temp");//上传文件目录 if (!uploadPath.exists()) { uploadPath.mkdirs(); } // 临时文件目录 File tempPathFile = new File("d:\\temp\\buffer\\"); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);//设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List items = upload.parseRequest(request);//得到所有的文件 Iterator 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); } } out.print("upload succeed"); } catch (Exception e) { e.printStackTrace(); } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> </body> </html> 示例4 利用Servlet来实现文件上传。 Upload.java package com.zj.sample; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings("serial") public class Upload extends HttpServlet { private String uploadPath = "D:\\temp"; // 上传文件的目录 private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录 File tempPathFile; @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);// 设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List items = upload.parseRequest(request);// 得到所有的文件 Iterator 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); } } System.out.print("upload succeed"); } catch (Exception e) { // 可以跳转出错页面 e.printStackTrace(); } } public void init() throws ServletException { File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } } demo4.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> // action="fileupload"对应web.xml中的设置. <form name="myform" action="fileupload" method="post" enctype="multipart/form-data"> File:
<input type="file" name="myfile"><br>
<input type="submit" name="submit" value="Commit"> </form> </body> </html> web.xml Upload com.zj.sample.Upload Upload /fileupload
文件的上传功能,只要自己构造一个servlet即可。 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setContentType(CONTENT_TYPE); // Set the servlet's response type to XML. PrintWriter out = null; String uploadDirectory = this.getServletContext().getInitParameter("UploadDirectory"); if(!uploadDirectory.contains(":")) { String rootpath = request.getRealPath(request.getRequestURI()); rootpath = rootpath.substring(0, rootpath .lastIndexOf("\\FlowMonitoringSystemJava\\uploadhandler")); uploadDirectory=rootpath+ uploadDirectory.replace('/', '\\'); } // Get the upload directory from the web.xml file. ArrayList allowedFormats = new ArrayList(); // Allowed image format types are stored in an ArrayList. allowedFormats.add("jpeg"); allowedFormats.add("png"); allowedFormats.add("gif"); allowedFormats.add("jpg"); File disk = null; FileItem item = null; DiskFileItemFactory factory = new DiskFileItemFactory(); // We use the FileUpload package provided by Apache to process the request. String statusMessage = ""; ListIterator iterator = null; List items = null; ServletFileUpload upload = new ServletFileUpload( factory ); // SAX 2.0 ContentHandler. TransformerHandler hd = null; try { out = response.getWriter(); StreamResult streamResult = new StreamResult(out); // Used for writing debug errors to the screen. SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); // SAX XML parsing factory. items = upload.parseRequest(request); iterator = items.listIterator(); hd = tf.newTransformerHandler(); // Set the XML handler. Transformer serializer = hd.getTransformer(); // You'll serialize the data. serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); // You'll use UTF-8 for the XML encoding. serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"response.dtd"); // Set the doctype to the custom DTD. serializer.setOutputProperty(OutputKeys.INDENT,"yes"); // Though not required, you can provide automatic indentation of the XML. serializer.setOutputProperty(OutputKeys.METHOD,"xml"); // Identifies the method used for outputting the result tree. hd.setResult(streamResult); hd.startDocument(); // Start the XML document. AttributesImpl atts = new AttributesImpl(); // Declare and instantiate a new attributes object. hd.startElement("","","response",atts); // Start the main response element. while( iterator.hasNext() ) // Loop over the items in the request. {

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧