我无法上传多个文件。我正在使用此代码。这里itr.hasNext()返回false。
FileUpload.jsp
<%@ page import="java.util.*" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<center>
<table border="2">
<tr>
<td>
<h1>Your files uploaded </h1>
</td>
</tr>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("isMultipart="+isMultipart);
System.out.println(config.getServletContext());
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
System.out.println(upload.parseRequest(request));
List items=null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem)(itr.next());
out.println("itr");
if (item.isFormField()) {
try{
String field=item.getFieldName();
String value=item.getString();
System.out.println("field="+value);
}
catch(Exception e){}
}
else {
try {
out.println("nor done");
String itemName = item.getName();
out.println("1done");
File savedFile = new File("/home/saurabh/assignments/"+itemName);
item.write(savedFile);
out.println("done");
} catch (Exception e) {
e.printStackTrace();
}
}
}
%>
</table>
</center>
html文件是: -
<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="FileUpload.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
<table border="2">
<tr>
<td align="center"><b>Multipale file Uploade</td>
</tr>
<tr>
<td>
Specify file: <input name="file" type="file" id="file">
<td>
</tr>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit files"/>
</td>
</tr>
</table>
<center>
</form>
</body>
</html>
这是如何引起的,我该如何解决?
答案 0 :(得分:3)
您正在解析请求两次。第一次打印项目,第二次真正获取项目进行处理。这不会起作用。它只能被解析一次。
删除以下无用的行
System.out.println(upload.parseRequest(request));
如果您真的打算出于某种原因打印已解析的项目,那么您应该
System.out.println(items);
在之后 您在try
块内部解析了请求。
无关,JSP不是这项工作的最佳选择。在servlet中完成这项工作,并将结果收集到您放入请求范围的某个map / bean中,然后将请求转发给JSP以显示结果。