Loading [MathJax]/extensions/tex2jax.js

2010-02-27

GWT+GAEでのファイルアップロード処理

とりあえず試してみたのでメモ書きです。本番環境で試してないのですが、たぶんおっけい?


クライアント側
下記のサンプルは、GWTのAPI仕様書(JavaDoc)に書かれている内容を参考にしてます。FileUploadウィジェットを用います。Formパネルの子としておかないとダメなのに注意。FileUploadウィジェットを用いれば、ファイルの選択などのGUIが用意されます。
public void onModuleLoad() {
// フォームパネルを宣言.これを使わないとダメです。
final FormPanel form = new FormPanel();
//どのURLへ飛ばすのか指定
form.setAction("/FileUploadServ");
// POSTの利用とmultipart MIME encodingであることを指定.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
// FileUploadウィジェットを宣言
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);
// Add a 'submit' button.
panel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
}));
// Add an event handler to the form.
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
// This event is fired just before the form is submitted. We can take
// this opportunity to perform validation.
//<ここでは未使用>
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
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 (see the FormPanel documentation for
// further explanation).
//<ここでは未使用>
}
});
RootPanel.get().add(form);
}
サーバー側

下記の例では、純粋なサーブレットですが、GAEでも動かすことを前提にしてます(本番環境では試してませんが)。ポイントは、FileItemStreamからInputStreamを生成しているところでしょうか。これで、ファイルタイプに応じていろんな対応ができるはずです。
なお、Apache のCommons FileUploadライブラリを仕様してます。
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, AuthenticationException, ServiceException {
try {
ServletFileUpload fileUpload = new ServletFileUpload();
FileItemIterator itemIterator = fileUpload.getItemIterator(request);
while (itemIterator.hasNext()) {
FileItemStream itemStream = itemIterator.next();
//ファイルタイプを調べる
String contentType =itemStream.getContentType();
InputStream inputStream = itemStream.openStream();
if(contentType==null){
contentType="";
}
else if(contentType.contains("image")){
//何かする
}
else if(contentType.contains("text")){
}
else{
}
} catch (FileUploadException e) {
response.sendError(500);
}
}

上記のプログラムでは、アップロード処理が終わった後の処理について書いてませんので、そこは各自で対応をお願いします。

2 件のコメント:

  1. すみません、これだけだと、どうやってアップロードしたファイルを読み込んだらいいのか分からないのですが、もう少し詳しく教えていただけませんか?

    processRequest()は、どこから呼ばれるんですか?onSubmitComplete()からですか?

    HttpServletRequest requestは、何処で定義されますか?requestの値は、どこからゲットしますか?

    すみませんが、宜しくお願いします。

    返信削除
  2. 1年前のコメに亀レスですが、processRequest()はdoGet(),doPost()の代替(同じ役割)です。Netbeans特有の書き方になります。

    返信削除