[b]1.在JSP页面中使用struts标签的文件上传:[/b]
[b]注:[/b]commons-fileupload.jar配置到struts-config.xml中
method:必须位POST方法
content:UpLoadForm 的属性
[b]2.UpLoadForm 文件[/b]
[b]3.UpLoadAction文件[/b]
[b]4.struts-config.xml文件配置[/b]
<html:form action="upload.do" enctype="multipart/form-data" methos="POST">
<html:file property="content"></html:file>
<html:submit>提交</html:submit>
</html:form>
[b]注:[/b]commons-fileupload.jar配置到struts-config.xml中
method:必须位POST方法
content:UpLoadForm 的属性
[b]2.UpLoadForm 文件[/b]
public class UpLoadForm extends ActionForm {
private FormFile content;
public FormFile getContent() {
return content;
}
public void setContent(FormFile content) {
this.content = content;
}
}
[b]3.UpLoadAction文件[/b]
public class UpLoadAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
// TODO Auto-generated method stub
//上传文本框所在的Form
UpLoadForm form = (UpLoadForm)actionForm;
//上传的内容被封装在Form中
FormFile content = form.getContent();
//获得上传的文件名
String fileName = content.getFileName();
//获取上传文件的大小
long size = content.getFileSize();
//网络输入流,流向服务器
InputStream in = content.getInputStream();
BufferedOutputStream out = null;
//获取工程的相对路径
String path=this.servlet.getServletConfig().getServletContext ().getRealPath("/");
//输出流,向服务器的硬盘写
out = new BufferedOutputStream(new FileOutputStream(path+"/WEB- INF/"+fileName));
byte[] buffer = new byte[512];
while((in.read(buffer))!=-1){
out.write(buffer, 0,buffer.length);
}
out.close();
return mapping.findForward("success");
}
}
[b]4.struts-config.xml文件配置[/b]
<form-beans>
<form-bean name="uploadForm" type="com.softeem.struts.Form.UpLoadForm"></form-bean>
</form-beans>
<action-mappings>
<action path="/upload" type="com.softeem.struts.Action.UpLoadAction" name="uploadForm" scope="request" validate="false" input="/UI/login.jsp">
<forward name="failure" path="/UI/failure.jsp"/>
<forward name="success" path="/bookList.do"/>
</action>
</action-mappings>