随笔 - 45, 文章 - 2, 评论 - 11, 引用 - 0
数据加载中……

翻译:使用Servlet实现文件上传

原文地址:http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm

 

一个Servlet可以通过HTML表单标签将文件上传到服务器。支待上传的有文本、图像及任何文件。

创建文件上传表单:

         下面的html代码创建了一个上传表单。创建过程需要注意以下几点:

form标签中的method属性必须设置为POST,即GET方法是不可以的。

form标签中的enctype属性应该设置为multipart/form-data

from标签中的action属性应该与服务器后台的servlet映射路径相同。接下来的实例,我们将使用UploadServlet实现文件上传。

要上传一个文件,你应该使用一个<input type=”file”.../>标记。要多个文件上传,必须包含多个具有不同的名称属性值的<input type=”file”.../>标记。The browser associates a Browse button with each of them

<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上选择一个文件。当你点击“Upload File”,表单将会随着你选择的文件一起被提交。

后台servlet

以下UploadServlet servlet将接收上传的文件并将其保存入<Tomcat-installation-directory>/webapps/data文件夹。这个文件夹的名称可以通过外部配置文件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>

         以下是实现了多文件同时上传功能的UploadServlet。在此之前您必须确定以下几点:

以下实例依赖F ileUpload类,所以您须将最新版的commons-fileupload.x.x.jar放到您的classpath下。可以从这里下载:http://commons.apache.org/fileupload/

FileUpload类依赖于Commons IO包,所以您须将最新版commons-fileupload.x.x.jar放到您的classpath下。可以从这里下载:http://commons.apache.org/io/

在测试以下例子的时候,您应该上传小于maxFileSize的文件,否则无法上传。

事先确定你已经建议好文件夹:c:"tempc:"apache-tomcat-5.5.29"webapps"data

// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;
 
public class UploadServlet extends HttpServlet {
   
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;
 
   public void init( ){
      // Get the file location where it would be stored.
      filePath = 
             getServletContext().getInitParameter("file-upload"); 
   }
   public void doPost(HttpServletRequest request, 
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
         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>");
         return;
      }
      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>Servlet 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();
            String contentType = fi.getContentType();
            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: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request, 
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
        
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   } 
}

       编译并运行Servlet

    编译以上UploadServlet并在web.xml中创建必须的实体,如下:

<servlet>
   <servlet-name>UploadServlet</servlet-name>
   <servlet-class>UploadServlet</servlet-class>
</servlet>
 
<servlet-mapping>
   <servlet-name>UploadServlet</servlet-name>
   <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

         现在可以尝试使用你创建的HTML表单上传文件。当你访问http://localhost:8080/UploadFile.htm,浏览器里将会显示如下效果,您可以从本地上传你想要上传的任何文件。

         如果您的servlet脚本运行成功,您的文件上传在c:"apache-tomcat-5.5.29"webapps"data"directory文件夹。

posted on 2011-03-23 08:52 jack zhai 阅读(3798) 评论(0)  编辑  收藏 所属分类: 翻译


只有注册用户登录后才能发表评论。


网站导航: