Struts文件上传
1. 页面配置:
<form action="upload.do" method="post" enctype="multipart/form-data">
标题:<input type="text" name="title"><br>
文件:<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
2. ActionForm中使用FormFile来接受上传文件,代码如下:
public class UploadForm extends
private FormFile file;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
}
3. 在Action中使用FormFile来接收上传文件,代码如下:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
ActionForward af = null;
UploadForm uploadForm = (UploadForm) form;// TODO Auto-generated method stub
FormFile myFile = uploadForm.getFile();
if(myFile!=null){
try {
FileOutputStream fos = new FileOutputStream("c://"+myFile.getFileName());
fos.write(myFile.getFileData());
fos.flush();
fos.close();
af = mapping.findForward("success");
} catch (Exception e) {
e.printStackTrace();
af = mapping.findForward("error");
}
}
return af;
}
4. 在struts-config.xml中的配置
配置form:
<form-bean name="uploadForm" type="com.zsw.struts.form.UploadForm" />
配置Action:
<action
attribute="uploadForm"
name="uploadForm"
path="/upload"
scope="request"
type="com.zsw.struts.action.UploadAction" >
<forward name="success" path="/upload_success.jsp" />
<forward name="error" path="/upload_error.jsp" />
</action>