99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

文件上傳

2018-08-12 21:19 更新

文件上傳

Servlet 可以與 HTML form 標簽一起使用允許用戶將文件上傳到服務器。上傳的文件可以是文本文件或圖像文件或任何文檔。

創(chuàng)建一個文件上傳表單

下述 HTML 代碼創(chuàng)建了一個文件上傳表單。以下是需要注意的幾點:

  • 表單 method 屬性應該設置為 POST 方法且不能使用 GET 方法。

  • 表單 enctype 屬性應該設置為 multipart/form-data.

  • 表單 action 屬性應該設置為 servlet 文件,能夠在后端服務器處理文件上傳。下面的例子是使用 UploadServlet servlet 來上傳文件的。

  • 要上傳單個文件,你應該使用單個帶有屬性 type=“file” 的 <input .../> 標簽。為了允許多個文件上傳,要包含多個帶有 name 屬性不同值的輸入標簽。瀏覽器將把一個瀏覽按鈕和每個輸入標簽關聯(lián)起來。
 
<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>

這將顯示如下所示的結果,允許從本地計算機中選擇一個文件,當用戶點擊“上傳文件”時,表單會和選擇的文件一起提交:

 
File Upload: 
Select a file to upload: 


NOTE: This is just dummy form and would not work.

編寫后臺 Servlet

以下是 servlet UploadServlet,會接受上傳的文件并把它儲存在目錄 <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 的源代碼,可以一次處理多個文件的上傳。在繼續(xù)操作之前,請確認下列各項:

  • 下述例子依賴于 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,否則文件將無法上傳。

  • 請確保已經(jīng)提前創(chuàng)建好目錄 c:\temp and c:\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

編譯上述 servlet UploadServlet 并在 web.xml 文件中創(chuàng)建所需的條目,如下所示:

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

現(xiàn)在嘗試使用上面創(chuàng)建的 HTML 表單來上傳文件。當你訪問 http://localhost:8080/UploadFile.htm 時,它會顯示如下所示的結果,這將有助于你從本地計算機中上傳任何文件。

 
File Upload: 

Select a file to upload:

如果你的 servelt 腳本能正常工作,那么你的文件會被上傳到 c:\apache-tomcat-5.5.29\webapps\data\ 目錄中。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號