GWT - 檔案上傳控制元件



簡介

FileUpload 控制元件封裝了 HTML <input type = 'file'> 元素。如果要將此控制元件提交到伺服器,則必須與 FormPanel 一起使用。

類宣告

以下是 com.google.gwt.user.client.ui.FileUpload 類的宣告:

public class FileUpload 
   extends Widget
      implements HasName, HasChangeHandlers

CSS 樣式規則

以下預設 CSS 樣式規則將應用於所有 TextBox 控制元件。您可以根據需要覆蓋它。

.gwt-FileUpload {}

類建構函式

序號 建構函式 & 描述
1

FileUpload()

構造一個新的檔案上傳控制元件。

2

FileUpload(Element element)

子類可以使用此建構函式顯式使用現有元素。

類方法

序號 函式名稱 & 描述
1

HandlerRegistration addChangeHandler(ChangeHandler handler)

新增 ChangeEvent 處理程式。

2

java.lang.String getFilename()

獲取使用者選擇的檔名。

3

java.lang.String getName()

獲取控制元件的名稱。

4

boolean isEnabled()

獲取此控制元件是否啟用。

5

void onBrowserEvent(Event event)

每當收到瀏覽器事件時觸發。

6

void setEnabled(boolean enabled)

設定此控制元件是否啟用。

7

void setName(java.lang.String name)

設定控制元件的名稱。

8

static FileUpload wrap(Element element)

建立一個 FileUpload 控制元件,包裝現有的 <input type='file'> 元素。

繼承的方法

此類繼承以下類的的方法:

  • com.google.gwt.user.client.ui.UIObject

  • com.google.gwt.user.client.ui.Widget

  • java.lang.Object

FileUpload 控制元件示例

此示例將引導您完成簡單的步驟,以展示如何在 GWT 中使用 FileUpload 控制元件。請按照以下步驟更新我們在GWT - 建立應用程式章節中建立的 GWT 應用程式:

步驟 描述
1 GWT - 建立應用程式章節中說明的基礎上,建立一個名為HelloWorld的專案,放在com.tutorialspoint包下。
2 修改HelloWorld.gwt.xmlHelloWorld.cssHelloWorld.htmlHelloWorld.java,如下所述。保持其餘檔案不變。
3 編譯並執行應用程式以驗證已實現邏輯的結果。

以下是修改後的模組描述符src/com.tutorialspoint/HelloWorld.gwt.xml的內容。

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to = 'helloworld'>
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- Specify the app entry point class.                         -->
   <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>

   <!-- Specify the paths for translatable code                    -->
   <source path = 'client'/>
   <source path = 'shared'/>

</module>

以下是修改後的樣式表文件war/HelloWorld.css的內容。

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
}

.gwt-FileUpload {
   color: green; 
}

以下是修改後的 HTML 宿主檔案war/HelloWorld.html的內容。

<html>
   <head>
      <title>Hello World</title>
      <link rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>FileUpload Widget Demonstration</h1>
      <div id = "gwtContainer"></div>
   </body>
</html>

讓我們看看 Java 檔案src/com.tutorialspoint/HelloWorld.java的內容,它將演示 FileUpload 控制元件的使用。

package com.tutorialspoint.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
      VerticalPanel panel = new VerticalPanel();
      //create a FormPanel 
      final FormPanel form = new FormPanel();
      //create a file upload widget
      final FileUpload fileUpload = new FileUpload();
      //create labels
      Label selectLabel = new Label("Select a file:");
      //create upload button
      Button uploadButton = new Button("Upload File");
      //pass action to the form to point to service handling file 
      //receiving operation.
      form.setAction("https://tutorialspoint.tw/gwt/myFormHandler");
      // set form to use the POST method, and multipart MIME encoding.
      form.setEncoding(FormPanel.ENCODING_MULTIPART);
      form.setMethod(FormPanel.METHOD_POST);
    
      //add a label
      panel.add(selectLabel);
      //add fileUpload widget
      panel.add(fileUpload);
      //add a button to upload the file
      panel.add(uploadButton);
      uploadButton.addClickHandler(new ClickHandler() {
         @Override
         public void onClick(ClickEvent event) {
            //get the filename to be uploaded
            String filename = fileUpload.getFilename();
            if (filename.length() == 0) {
               Window.alert("No File Specified!");
            } else {
               //submit the form
               form.submit();			          
            }				
         }
      });
   
      form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
         @Override
         public void onSubmitComplete(SubmitCompleteEvent event) {
            // When the form submission is successfully completed, this 
            //event is fired. Assuming the service returned a response 
            //of type text/html, we can get the result text here 
            Window.alert(event.getResults());				
         }
      });
      panel.setSpacing(10);
	  
      // Add form to the root panel.      
      form.add(panel);      

      RootPanel.get("gwtContainer").add(form);
   }	
}

完成所有更改後,讓我們像在GWT - 建立應用程式章節中一樣,在開發模式下編譯並執行應用程式。如果應用程式一切正常,則會產生以下結果:

GWT FileUpload Widget

以下是演示檔案上傳伺服器端功能的 Java 伺服器頁面程式碼片段。我們使用Common IOCommons FileUpload庫來為伺服器端頁面新增檔案上傳功能。檔案將上傳到伺服器端 upload.jsp 所在位置的相對路徑 uploadFiles 資料夾。

<%@page import = "org.apache.commons.fileupload.FileItemFactory"%>
<%@page import = "org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import = "org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import = "org.apache.commons.fileupload.FileItem"%>
<%@page import = "org.apache.commons.io.FilenameUtils"%>
<%@page import = "java.util.List"%>
<%@page import = "java.util.Iterator"%>
<%@page import = "java.io.File"%>
<%@page import = "java.io.FileOutputStream"%>
<%@page import = "java.io.InputStream"%>

<%
   // Create a factory for disk-based file items
   FileItemFactory factory = new DiskFileItemFactory();
   // Create a new file upload handler
   ServletFileUpload upload = new ServletFileUpload(factory);
   try {
      // Parse the request
         List items = upload.parseRequest(request); 

      // Process the uploaded items
         Iterator iter = items.iterator();

      while (iter.hasNext()) {
         FileItem item = (FileItem) iter.next();
      
         //handling a normal form-field
         if(item.isFormField()) {
            System.out.println("Got a form field");
            String name = item.getFieldName();
            String value = item.getString();
            System.out.print("Name:"+name+",Value:"+value);				
         
         } else { 
            
            //handling file loads
            System.out.println("Not form field");
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            if (fileName != null) {
               fileName = FilenameUtils.getName(fileName);
            }
            
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();
            System.out.print("Field Name:"+fieldName +",File Name:"+fileName);
            System.out.print("Content Type:"+contentType
               +",Is In Memory:"+isInMemory+",Size:"+sizeInBytes);			 
            
            byte[] data = item.get();
            fileName = getServletContext()
               .getRealPath( "/uploadedFiles/" + fileName);
            System.out.print("File name:" +fileName);			
            FileOutputStream fileOutSt = new FileOutputStream(fileName);
            fileOutSt.write(data);
            fileOutSt.close();
            out.print("File Uploaded Successfully!");
         }	
      }
   } catch(Exception e){
      out.print("File Uploading Failed!" + e.getMessage());
   }   
%>
gwt_form_widgets.htm
廣告

© . All rights reserved.