在 struts1 中,上传文件很方便,使用FormFile接口。
1. 在 jsp 中创建表单。注意:上传时必须用 post 提交方式,另外,enctype属性必须有。
- <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="上传">
- </form>
2. 定义ActionForm。文件变量的声明必须使用FormFile。
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.upload.FormFile;
- @SuppressWarnings("serial")
- public class UploadActionForm extends ActionForm {
- private String title;
- // 上传的文件必须采用FormFile声明
- 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;
- }
- }
3. 写个测试类TestAction。
- import java.io.FileOutputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.Action;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- public class UploadTestAction extends Action {
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- UploadActionForm uaf = (UploadActionForm)form;
- System.out.println("title=" + uaf.getTitle());
- System.out.println("filename=" + uaf.getMyfile().getFileName());
- FileOutputStream fos = new FileOutputStream("d:\\" + uaf.getMyfile().getFileName());
- fos.write(uaf.getMyfile().getFileData());
- fos.flush();
- fos.close();
- return mapping.findForward("success");
- }
- }
4. 上传成功后跳转的 jsp。
- <body>
- 上传成功!<br>
- 标题=【${uploadForm.title }】<br>
- 文件名称=【${uploadForm.myfile.fileName }】
- </body>
5. 配置struts_config。
- <struts-config>
- <form-beans>
- <form-bean name="uploadForm" type="com.tzhuwb.struts.UploadActionForm"/>
- </form-beans>
- <action-mappings>
- <action path="/upload"
- type="com.tzhuwb.struts.UploadTestAction"
- name="uploadForm"
- scope="request">
- <forward name="success" path="/upload_success.jsp"></forward>
- </action>
- </action-mappings>
- <controller maxFileSize="50M"/>
- </struts-config>