发布于 2015-08-17 14:49:22 | 250 次阅读 | 评论: 0 | 来源: 网络整理

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

创建一个文件上传表单:

下面的下面的HTM代码创建了一个上传表单。以下是要点要注意下:

  • 该表单方法属性应设置为POST方法,而GET方法无法使用。

  • 表单enctype属性应该设置为multipart/ form-data。

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

  • 要上传一个文件,你应该使用一个单一的<input.../>标签与属性 type="file"。以允许多个文件上传,包括一个以上的输入变量作为名称属性的不同值。浏览器关联到他们每个人的浏览按钮。


 
<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>

这将显示如下结果将允许从本地电脑中选择一个文件,当用户点击在"Upload File",形式会随着所选择的文件提交:


 
File Upload: 
Select a file to upload: 
<input name="file" size="50" style="font-family: inherit;" type="file" />
<input style="font-family: inherit;" type="button" value="Upload File" />
 

注:以上表格仅仅是虚拟的形式和是行不通的,应该尝试上面的代码在你的机器,使其工作。

写作后端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.29webappsdata
     </param-value> 
</context-param>
....
</web-app>

以下是源代码UploadFile.jsp它可以同时处理多个文件上传。继续操作之前,已确认下列各项:

  • 下面的例子依赖于的FileUpload,所以一定要确保commons-fileupload.x.x.jar文件的最新版本在你的classpath中。你可以从这里下载 http://commons.apache.org/fileupload/.

  • FileUpload依赖于共享IO,所以一定要确保你有commons-io-x.x.jar文件在你的类路径中的最新版本。你可以从这里下载 http://commons.apache.org/io/.

  • 而下面的例子测试,你应该上传的文件应该小于maxFileSizeotherwise,否则文件将无法上传。

  • 请确保您已创建的目录 c:temp 和  c:apache-tomcat-5.5.29webappsdata 


<%@ 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.html,它会显示以下结果,这将有助于从本地计算机上传文件。


 
File Upload: 
Select a file to upload: 
 
 

 
 

如果JSP脚本能正常工作,文件应该上传到 c:apache-tomcat-5.5.29webappsdata 目录下.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务