struts中含有支持文件上传功能的包org.apache.struts.upload。可以创建一个包含FormFile类型的属性的ActionForm。如:
package cn.rolia.struts.upload;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm {
private FormFile theFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getTheFile() {
return theFile;
}
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}
}
然后在对应JSP文件中使用html:file标记。要上传文件,html:form标记的enctype属性必须是” multipart/form-data”且方法必须是POST。如:
<body>
文件上传实例 <HR>
<center>
<html:form action="/upload" method="POST" enctype="multipart/form-data">
select the file you want to upload.<br/>
<html:file property="theFile"></html:file><br/>
<html:submit></html:submit><html:reset></html:reset>
</html:form>
</center>
</body>
在控制层处理保存上传文件Action里,调用FormFile的getInputStream方法获得上传文件的数据流然后进行保存。
评论