橘子味的心
标题:JSP上传文件

在本章中,我们将讨论和学习如何在JSP中的文件上传。 JSP可以与HTML表单标签一起使用,以允许用户将文件上传到服务器。上传的文件可以是文本文件或二进制文件或图像文件,也可以是任何文档。

为了方便演示,首先打开Eclipse创建一个动态Web项目:UploadFile ,其目录结构如下所示 -

创建文件上传表单

现在来看看如何创建一个文件上传表单。 以下HTML代码创建一个上传器表单。 以下是要注意的重点 -

  • 表单中的method属性应设置为POST方法,不能使用GET方法。
  • 表单中的enctype属性应设置为multipart/form-data
  • 表单中的action属性应该设置为一个JSP文件,它将处理后端服务器上的文件上传。 以下示例 - 使用uploadhandle.jsp程序处理上传文件。

要上传单个文件,应该在单个<input ... />标签中指定使用type ="file"属性。 要允许多个文件上传,请将name属性包含多个具有不同值的输入标记。浏览器将浏览按钮与每个浏览器相关联。

文件:selectFile.html文件代码如下 -

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>文件上传示例</title>
  6. </head>
  7. <body>
  8. <div style="margin: auto; width: 80%;">
  9. <h3>文件上传示例</h3>
  10. 选择要上传的文件:
  11. <form action="uploadhandle.jsp" method="post" enctype="multipart/form-data">
  12. <input type="file" name="file" size="50" /><input
  13. type="submit" value="提交上传" />
  14. </form>
  15. </div>
  16. </body>
  17. </html>
  18. HTML

这将显示以下结果。现在可以从本地电脑选择一个文件,并且当用户单击“上传文件”时,表单将随所选文件一起提交 -

注意 - 上面的表单只是虚拟表单,不起作用,要处理上传还需要编写JSP相关处理文件上传的程序。

后端JSP脚本

现在定义一个存储上传文件的位置。可以在程序中对此进行硬编码,也可以使用外部配置(如web.xml中的context-param元素)添加此目录名称,如下所示:

以下是uploadFile.jsp的源代码。这可以一次处理多个文件的上传。 在继续上传文件之前,需要考虑以下几点:

  • 以下示例依懒于FileUpload类库; 确保类路径中有最新版本的commons-fileupload.x.x.jar文件(可以从 http://commons.apache.org/fileupload/ 下载)。
  • FileUpload类库依懒于Commons IO;确保类路径中有最新版本的commons-io-x.x.jar文件(可以从 http://commons.apache.org/io/ 下载)。
  • 在测试以下示例时,应该将上传的文件大小小于maxFileSize,否则文件将不会被上传。
  • 这个项目中是将文件上传到项目部署的目录下,但您可配置并创建目录c:\tempc:\apache-tomcat8.5.29\webapps\data或指定到其位置。

文件:uploadhandle.jsp 的代码实现如下 -

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
  4. <%@ page import="javax.servlet.http.*"%>
  5. <%@ page import="org.apache.commons.fileupload.*"%>
  6. <%@ page import="org.apache.commons.fileupload.disk.*"%>
  7. <%@ page import="org.apache.commons.fileupload.servlet.*"%>
  8. <%@ page import="org.apache.commons.io.output.*"%>
  9.  
  10. <%
  11. File file;
  12. int maxFileSize = 5000 * 1024;
  13. int maxMemSize = 5000 * 1024;
  14. ServletContext context = pageContext.getServletContext();
  15. //String filePath = context.getInitParameter("file-upload");
  16. String filePath = request.getSession().getServletContext().getRealPath("");
  17. //String filePath = request.getContextPath();
  18. System.out.println("filePath => " + filePath);
  19. // Verify the content type
  20. String contentType = request.getContentType();
  21.  
  22. if (contentType == null) {
  23. System.out.println("contentType => " + contentType);
  24. contentType = "";
  25. }
  26. if ((contentType.indexOf("multipart/form-data") >= 0)) {
  27. DiskFileItemFactory factory = new DiskFileItemFactory();
  28. // maximum size that will be stored in memory
  29. factory.setSizeThreshold(maxMemSize);
  30.  
  31. // Location to save data that is larger than maxMemSize.
  32. factory.setRepository(new File("c:\\temp"));
  33.  
  34. // Create a new file upload handler
  35. ServletFileUpload upload = new ServletFileUpload(factory);
  36.  
  37. // maximum file size to be uploaded.
  38. upload.setSizeMax(maxFileSize);
  39.  
  40. try {
  41. // Parse the request to get file items.
  42. List fileItems = upload.parseRequest(request);
  43.  
  44. // Process the uploaded file items
  45. Iterator i = fileItems.iterator();
  46.  
  47. out.println("<html>");
  48. out.println("<head>");
  49. out.println("<title>JSP File upload</title>");
  50. out.println("</head>");
  51. out.println("<body>");
  52.  
  53. while (i.hasNext()) {
  54. FileItem fi = (FileItem) i.next();
  55. if (!fi.isFormField()) {
  56. // Get the uploaded file parameters
  57. String fieldName = fi.getFieldName();
  58. String fileName = fi.getName();
  59. boolean isInMemory = fi.isInMemory();
  60. long sizeInBytes = fi.getSize();
  61.  
  62. // Write the file
  63. if (fileName.lastIndexOf("\\") >= 0) {
  64. file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
  65. } else {
  66. file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
  67. }
  68. fi.write(file);
  69. out.println("Uploaded Filename: " + filePath + fileName + "<br>");
  70. }
  71. }
  72. out.println("</body>");
  73. out.println("</html>");
  74. } catch (Exception ex) {
  75. System.out.println(ex);
  76. }
  77. } else {
  78. out.println("<html>");
  79. out.println("<head>");
  80. out.println("<title>Servlet upload</title>");
  81. out.println("</head>");
  82. out.println("<body>");
  83. out.println("<p>No file uploaded</p>");
  84. out.println("</body>");
  85. out.println("</html>");
  86. }
  87. %>
  88. HTML

现在尝试使用上面创建的HTML表单上传文件。部署项目后,打开浏览器访问URL: http://localhost:8080/UploadFile/selectFile.html 时将显示以下结果。

如果编写的JSP脚本工作正常,选择的文件应该上传到项目的根目录中。