Struts2入門ファイルアップロードを実現するサンプルコード

1.Fileupload.java
public class Fileupload extends ActionSupport {
private File upload;
private String uploadContentType;
private String uploadFileName;
private String title;

private String savePath;

public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}

@Override
public String execute() throws Exception {
System.out.println(getSavePath());
FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
FileInputStream fis=new FileInputStream(getUpload());
byte[] buffer=new byte[1024];
int len=0;
while((len=fis.read(buffer))>0)
{
fos.write(buffer,0,len);
}

// TODO Auto-generated method stub
return SUCCESS;
}

}

2.Formの定義
<s:form action="startnews24/upload" enctype="multipart/form-data" method="post">
<s:textfield name="title" label="title" />
<s:file name="upload" label="選択"/>
<s:submit value="submit"/>
</s:form>

3.ファイルフィルタの定義
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/png.image/gif,image/jpeg</param>
<param name="maximumSize">3000</param>
</interceptor-ref>
<result name="input">/exception.jsp</result>
<interceptor-ref name="defaultStack"/>

Java

Posted by arkgame