JSP的文件上传

以下内容引用自http://wiki.jikexueyuan.com/project/jsp/file-uploading.html

一个JSP可以用一个HTML表单标签,它允许用户上传文件到服务器。上传的文件是一个文本文件或二进制文件,图像文件或任何文件。

一、创建文件上传形式

用下面的HTM代码创建一个上传表单。以下的要点应该记下来:

  • 表单method的属性应该设置为POST方法,不能使用GET方法。
  • 表单enctype的属性应该设置为multipart/formdata。

  • 表单action的属性应该设置为一个把文件上传到后台服务器的JSP文件。下面的例子是使用程序uploadFile.jsp来上传文件。

  • 为了上传一个单一的文件,应该使用一个带有属性type="file"的<input .../>标签。为了允许多个文件上传,包含多个输入标签,它们带有不同的name属性的值。浏览器将浏览按钮与每个输入标签进行关联。

示例:

前台main.html

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadFile.jsp" method="post" enctype="multipart/form-data">
  <input type="file" name="file" size="50" />
  <br />
  <input type="submit" value="Upload File" />
</form>
</body>
</html>

后台UploadFile.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,所以确保在classpath中有最新的版本commons-fileupload.x.x.jar文件。可以从http://commons.apache.org/fileupload/中下载它。

  • FileUpload取决于Commons IO,所以确保在classpath中有最新的版本commons-io-x.x.jar文件。可以从http://commons.apache.org/io/中下载它。

  • 当测试下面的例子时,应该上传小于maxFileSize的文件,否则文件不能上传。

  • 确保提前创建好目录c:\temp和c:\apache-tomcat-5.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/main.htm,它将显示如下结果:

如果JSP script运行良好,文件应该上传到c:\apache-tomcat-5.5.29\webapps\data\directory 中。

 

测试工程:https://github.com/easonjim/5_java_example/tree/master/jspbasics/test11

posted @ 2017-06-07 00:54  EasonJim  阅读(500)  评论(0编辑  收藏  举报