JSP - 文件上传( File Uploading)
在本章中,我们将讨论JSP中的文件上载。 JSP可以与HTML表单标记一起使用,以允许用户将文件上载到服务器。 上传的文件可以是文本文件,也可以是二进制文件或图像文件,也可以是任何文档。
创建文件上载表单
现在让我们了解如何创建文件上载表单。 以下HTML代码创建了一个上传器表单。 以下是需要注意的重点 -
表单method属性应设置为POST方法,并且不能使用GET方法。
表单enctype属性应设置为multipart/form-data 。
表单action属性应设置为JSP文件,该文件将处理后端服务器上的文件上载。 以下示例是使用uploadFile.jsp程序文件上传文件。
要上传单个文件,您应该使用带有属性type = "file"的单个《input .../》标记。 要允许多个文件上载,请包含多个具有不同name属性值的输入标记。 浏览器将“浏览”按钮与每个按钮相关联。
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "UploadServlet" method = "post"
enctype = "multipart/form-data">
<input type = "file" name = "file" size = "50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
这将显示以下结果。 您现在可以从本地PC中选择一个文件,当用户单击“上传文件”时,表单将与所选文件一起提交 -
<b class="notranslate">File Upload</b> −
<p>Select a file to upload −</p>
<input type="file" name="file" size="50">
<input type="button" value="Upload File">
NOTE - 上面的表单只是虚拟表单,不起作用,你应该尝试在你的机器上面的代码使其工作。
编写后端JSP脚本
现在让我们定义一个存储上传文件的位置。 您可以在程序中对此进行硬编码,也可以使用外部配置(例如web.xml中的context-param元素)添加此目录名,如下所示 -
<web-app>
....
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:\apache-tomcat-5.5.29\webapps\data\
</param-value>
</context-param>
....
</web-app>
以下是UploadFile.jsp的源代码。 这可以一次处理多个文件的上传。 现在让我们在继续上传文件之前考虑以下事项。
以下示例依赖于FileUpload ; 确保在类路径中有最新版本的commons-fileupload.xxjar文件。 您可以从https://commons.apache.org/fileupload/下载它。
FileUpload依赖于Commons IO; 确保在类路径中有最新版本的commons-io-xxjar文件。 您可以从https://commons.apache.org/io/下载。
在测试以下示例时,您应该上传一个比maxFileSize的文件,否则不会上传该文件。
确保您提前创建了目录c:\temp和c:\apache-tomcat5.5.29\webapps\data 。
<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () ) {
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () ) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ) {
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
} else {
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
System.out.println(ex);
}
} else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
现在尝试使用您在上面创建的HTML表单上传文件。 当您尝试http://localhost:8080/UploadFile.htm ,它将显示以下结果。 这将帮助您从本地计算机上传任何文件。
<b class="notranslate">File Upload</b> −
<p>Select a file to upload −</p>
<input type="file" name="file" size="50">
<input type="button" value="Upload File">
如果您的JSP脚本正常工作,您的文件应该上传到c:\apache-tomcat5.5.29\webapps\data\目录。