form表单:
<li>测试strutsh上传</li><br>
<form action="upload.do" method="post" enctype="multipart/form-data">
标题:<input type="text" name="title"/><br>
文件:<input type="file" name="myfile" /><br>
<input type="submit" value="上传" name="submit"><br>
</form>
--------------------------------------------------------------------------------------------------------------
ActionForm:
package com.bjsxt.struts;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
/**
* 上传ActionForm
* @author Administrator
*
*/
public class UploadActionForm extends ActionForm {
private String title;
private FormFile myfile;
//
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public FormFile getMyfile() {
return myfile;
}
public void setMyfile(FormFile myfile) {
this.myfile = myfile;
}
}
-------------------------------------------------------
UploadAction
public class UploadTestAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UploadActionForm uaf=(UploadActionForm)form;
String title=uaf.getTitle();
FormFile myfile=uaf.getMyfile();
//
System.out.println("title="+title);
//
if(myfile!=null)
{
//将文件保存到磁盘
System.out.println("filename="+myfile.getFileName());
FileOutputStream fos=new FileOutputStream("c://"+myfile.getFileName());
fos.write(myfile.getFileData());//byte[] getFileData()传回的数据为整个文件作为字节数组。
fos.flush();//flush()是数据在内存上了,只有flush一下才能从内存读到磁盘上
fos.close();
}
return mapping.findForward("success");
}
}
-------------------------------------------------------------------------------------------
struts-config.xml
<form-beans>
<form-bean name="dynaActionForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="name" type="java.lang.String" />
<form-property name="age" type="java.lang.Integer" />
</form-bean>
<form-bean name="UploadForm" type="com.bjsxt.struts.UploadActionForm" />
</form-beans>
<action-mappings>
<action path="/dynaactionform"
type="com.bjsxt.struts.DynaActionFormTestAction"
name="dynaActionForm"
scope="request"
>
<forward name="success" path="/dynaactionform_success.jsp" />
</action>
<action path="/upload"
type="com.bjsxt.struts.UploadTestAction"
name="UploadForm"
scope="request"
>
<forward name="success" path="/upload_success.jsp"></forward>
</action>
</action-mappings>
<controller maxFileSize="10M" /><!--文件上传的大小-->
--------------------------------------------------------------------------------------------------
从ActionForm中取出数据
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>上传文件成功</title>
</head>
<body>
上传文件成功<br>
标题:${UploadForm.title }<br>
文件名:${UploadForm.myfile.fileName }<br>
</body>
</html>