您好,您应该在表单页面中有enctype="multipart/form-data ,如下所示。
上传表单 HTML:
<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="./index.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>
<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit files"/>
</td>
</tr>
</table>
<center>
</form>
</body>
</html>
上传 JSP:
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.io.File" %>
<%@ 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);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
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();
if (item.isFormField()) {
} else {
try {
String itemName = item.getName();
File savedFile = new File("C:\\ealvin@hp.com\\upload\\"+itemName);
item.write(savedFile);
out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
</table>
</center>