Gwt-fileupload-widget
GWT-FileUploadウィジェット
前書き
*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 {}
クラスコンストラクター
Sr.No. | Constructor & Description |
---|---|
1 |
FileUpload() 新しいファイルアップロードウィジェットを作成します。 |
2 |
FileUpload(Element element) このコンストラクタは、既存の要素を明示的に使用するためにサブクラスによって使用される場合があります。 |
クラスメソッド
Sr.No. | Function name & Description |
---|---|
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) 既存の<input type = 'file'>要素をラップするFileUploadウィジェットを作成します。 |
継承されるメソッド
このクラスは、次のクラスからメソッドを継承します-
- com.google.gwt.user.client.ui.UIObject
- com.google.gwt.user.client.ui.Widget
- java.lang.Object
FileUploadウィジェットの例
この例では、GWTでFileUploadウィジェットの使用方法を示す簡単な手順を紹介します。 次の手順に従って、_GWTで作成したGWTアプリケーションを更新します-アプリケーションの作成_の章-
Step | Description |
---|---|
1 | Create a project with a name HelloWorld under a package com.finddevguides as explained in the GWT - Create Application chapter. |
2 | Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorldl and HelloWorld.java as explained below. Keep rest of the files unchanged. |
3 | Compile and run the application to verify the result of the implemented logic. |
以下は、変更されたモジュール記述子 src/com.finddevguides/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.finddevguides.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/HelloWorldl の内容です。
<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>
FileUploadウィジェットの使用法を示すJavaファイル src/com.finddevguides/HelloWorld.java の内容を見てみましょう。
package com.finddevguides.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("http://www.finddevguides.com/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);
}
}
すべての変更が完了したら、link:/gwt/gwt_create_application [GWT-アプリケーションの作成]の章で行ったように、アプリケーションをコンパイルして開発モードで実行します。 すべてがあなたのアプリケーションでうまくいけば、これは次の結果を生成します-
以下は、サーバー側のファイルアップロード機能を示すJavaサーバーページコードスニペットです。 Common IOおよびhttps://commons.apache.org/fileupload/[Commons 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());
}
%>