4月 7th, 2008at 13:42

Tags: ,

Struts1.3.5でファイルアップロード

このエントリーをはてなブックマークに追加

Strutsでは簡単にファイルアップロードができる。

Formを用意する

StrutsではファイルをFormFileクラスで操作する。Formにはこのゲッター、セッターを作ればいいだけ。

 private FormFile file; public FormFile getFile() {     return file; }

 public void setFile(FormFile file) {     this.file = file; }

ファイルアップロードAction 

FormFile.getInputStream()でInputStreamが取得できるので、これを使って、ファイルに書き出したり、よきにはからえばいい。

下の例では、メモリ上にロードしている。

   FormFile formFile = f.getFile();

   if(formFile != null){

       InputStream is = null;       BufferedInputStream bis = null;       ByteArrayOutputStream baos = null;       BufferedOutputStream bos = null;

       try{           is = formFile.getInputStream();           bis = new BufferedInputStream(is, 1024);

           baos = new ByteArrayOutputStream(1024);           bos = new BufferedOutputStream(baos);

           int data = 0;           while((data = bis.read()) != -1){               bos.write(data);           }

           bos.flush();

           //TODO           logger.trace(baos.toString());

       }catch(FileNotFoundException fnfe){           fnfe.printStackTrace();           return map.findForward("error);

       }catch(IOException ioe){           ioe.printStackTrace();           return map.findForward("error);

       }finally{           try{               bos.close();               //baos.close();               bis.close();               is.close();

               formFile.destroy();

           }catch(IOException ioe){               ioe.printStackTrace();               return map.findForward("error);           }       }   }

   return map.findForward("sucess);   

JSPの記述

フォームタグのenctype属性に「multipart/form-data」を指定しなければならない。これを忘れるとJSPを表示したときに真っ白になってしまう。

<html:form action="/UploadAction" enctype="multipart/form-data">

struts-config.xmlの設定

struts-config.xmlではファイルアップロードの設定ができる。action-mappingタグとmessage-resourceタグの間にcontrollerタグを記述。ファイルの最大数、バッファのサイズ、一時フォルダの指定が可能。

 <controller maxFileSize="500K"             bufferSize="500"             tempDir="c:/temp" />

QA 

画面が真っ白に

html:fileタグを使ってるフォームには「enctype=”multipart/form-data」を指定しないとダメ。これやらないと真っ白の画面が表示されるみたい。

このエントリーをはてなブックマークに追加