fileLoad.jsp
代码如下:
uri="/WEB-INF/struts-logic.tld" prefix="logic"
%>
prefix="bean" %>
prefix="html" %>
%>
fileLoad.jsp
JBuilder Generated Struts JSP for
ActionForm forms.LoadForm
enctype="multipart/form-data">
property="file"/>
/>//对应于ActionFrom的FormFile file属性。
value="Submit"/>
property="fname">
name:
property="fname"/>
size:
property="size"/>
LoadForm的代码:
package forms;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class LoadForm extends ActionForm {
private
FormFile file;
private
String fname;
private
String size;
public
FormFile getFile() {
return file;
}
public
void setFile(FormFile file) {
this.file = file;
}
public
void setSize(String size) {
this.size = size;
}
public
void setFname(String fname) {
this.fname = fname;
}
public
String getFname() {
return fname;
}
public
String getSize() {
return size;
}
public
ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
return null;
}
public
void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
}
}
LoginAction代码如下:
package actions;
import
org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import forms.LoadForm;
import org.apache.struts.action.Action;
import org.apache.struts.upload.FormFile;
import java.io.*;
public class LoadAction extends Action {
public
ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse)throws Exception {
LoadForm loadForm = (LoadForm) actionForm;
FormFile ff=loadForm.getFile();
if(ff==null)
{
return actionMapping.findForward("success");
}
String fname=ff.getFileName();
String size=Integer.toString(ff.getFileSize())+"bytes";
InputStream in=ff.getInputStream();
OutputStream out=new FileOutputStream("/"+fname);
int bytesRead=0;
byte[] buffer=new byte[8192];
while((bytesRead=in.read(buffer,0,8192))!=-1)
{
out.write(buffer,0,bytesRead);
}
out.close();
in.close();
loadForm.setFname(fname);
loadForm.setSize(size);
ff.destroy();
return actionMapping.findForward("success");
}
}
struts-config.xml代码:
encoding="UTF-8"?>
/p>
Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
/>
scope="request" type="actions.LoadAction"
input="/fileLoad.jsp">
path="/fileLoad.jsp">
说明:标签可以方便的实现文件上传功能。
有以下几点需要注意:
1:
必须嵌套在标签中。
2:
标签的method的属性必须设为"post".3:
标签的编码类型enctype属性必须为"multipart/form-data"。4:标签必须设为property属性,这个属性和ActionForm
Bean中FormFile类型的属性对应。