Struts1中上传文件的简单使用
2014年03月29日 15:57:51 Struts ⁄ 共 2452字 暂无评论 ⁄ 被围观 1,820次

在 struts1 中,上传文件很方便,使用FormFile接口。

1. 在 jsp 中创建表单。注意:上传时必须用 post 提交方式,另外,enctype属性必须有。

Code   ViewPrint
  1. <form action="upload.do" method="post" enctype="multipart/form-data">
  2.     标题:<input type="text" name="title"><br>
  3.     文件:<input type="file" name="myfile"><br>
  4.     <input type="submit" value="上传">
  5. </form>

2. 定义ActionForm。文件变量的声明必须使用FormFile。

Code   ViewPrint
  1. import org.apache.struts.action.ActionForm;
  2. import org.apache.struts.upload.FormFile;
  3. @SuppressWarnings("serial")
  4. public class UploadActionForm extends ActionForm {
  5.     private String title;
  6.     // 上传的文件必须采用FormFile声明
  7.     private FormFile myfile;
  8.     public String getTitle() {
  9.         return title;
  10.     }
  11.     public void setTitle(String title) {
  12.         this.title = title;
  13.     }
  14.     public FormFile getMyfile() {
  15.         return myfile;
  16.     }
  17.     public void setMyfile(FormFile myfile) {
  18.         this.myfile = myfile;
  19.     }
  20. }

3. 写个测试类TestAction。

Code   ViewPrint
  1. import java.io.FileOutputStream;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.apache.struts.action.Action;
  5. import org.apache.struts.action.ActionForm;
  6. import org.apache.struts.action.ActionForward;
  7. import org.apache.struts.action.ActionMapping;
  8. public class UploadTestAction extends Action {
  9.     @Override
  10.     public ActionForward execute(ActionMapping mapping, ActionForm form,
  11.             HttpServletRequest request, HttpServletResponse response)
  12.             throws Exception {
  13.         UploadActionForm uaf = (UploadActionForm)form;
  14.         System.out.println("title=" + uaf.getTitle());
  15.         System.out.println("filename=" + uaf.getMyfile().getFileName());
  16.         FileOutputStream fos = new FileOutputStream("d:\\" + uaf.getMyfile().getFileName());
  17.         fos.write(uaf.getMyfile().getFileData());
  18.         fos.flush();
  19.         fos.close();
  20.         return mapping.findForward("success");
  21.     }
  22. }

4. 上传成功后跳转的 jsp。

Code   ViewPrint
  1. <body>
  2.     上传成功!<br>
  3.     标题=【${uploadForm.title }】<br>
  4.     文件名称=【${uploadForm.myfile.fileName }】
  5. </body>

5. 配置struts_config。

Code   ViewPrint
  1. <struts-config>
  2.     <form-beans>
  3.         <form-bean name="uploadForm" type="com.tzhuwb.struts.UploadActionForm"/>
  4.     </form-beans>
  5.     <action-mappings>
  6.         <action path="/upload"
  7.                 type="com.tzhuwb.struts.UploadTestAction"
  8.                 name="uploadForm"
  9.                 scope="request">
  10.             <forward name="success" path="/upload_success.jsp"></forward>
  11.         </action>
  12.     </action-mappings>
  13.     <controller maxFileSize="50M"/>
  14. </struts-config>

给我留言

留言无头像?