现在的位置: 首页 > 综合 > 正文

struts实现文件上传程序

2013年05月10日 ⁄ 综合 ⁄ 共 2022字 ⁄ 字号 评论关闭

 /**
*
* Struts文件上传程序
*
**/

JSP表单文件上传框

首先ActionForm 类创建要有返回指定为FormFile 对象的对应上传文件表单属性

public class UploadFileActionForm extends ActionForm {
 private String name;
 private FormFile myfile;    //myfile必须对应表单属性名,FormFile 特指定返回的对象
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public FormFile getMyfile() {
  return myfile;
 }
 public void setMyfile(FormFile myfile) {
  this.myfile = myfile;
 }
}

----------------------------------------------------------

Action 类处理要有负责输出上传文件流;
通过FormFile 对象可以取得各方法,例如formfile.getFileData()为返回Byte型数组,可以直接写输出流

public class UploadFileAction extends Action {

 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  
  UploadFileActionForm ufaf=(UploadFileActionForm) form;
  String name=ufaf.getName();
  FormFile formfile=ufaf.getMyfile();
 
  if(formfile!=null){
   //创建本地服务器端输出流
   FileOutputStream fos=new FileOutputStream("d://"+formfile.getFileName());
   //写入数据formfile.getFileData()直接获取的是字节数组
   fos.write(formfile.getFileData());
   fos.flush();
   fos.close();
   return mapping.findForward("success");
  }else{
   return mapping.findForward("fail");
  }
 }
}
--------------------------------------------------------
在struts-config.xml文件中加入<controller maxFileSize="10m"/>可限制上传文件大小,单位有K M G

<struts-config>
 <form-beans>
        <form-bean
            name="uploadfileForm"
            type="uploadfile.UploadFileActionForm"/>
           
    </form-beans>
 
    <action-mappings>
        <action
            path="/uploadfile"
            type="uploadfile.UploadFileAction"
            name="uploadfileForm"
            scope="request"
            >
           <forward name="success" path="/uploadfilesuccess.jsp"/>
           <forward name="fail" path="/uploadfilefail.jsp"/>
            </action>           
    </action-mappings>

 <controller maxFileSize="10m"></controller>  <!--  控制上传文件最大值-->
 
</struts-config>

----------------------------------------------------------
表现层输出JSP:

    title: ${uploadfileForm.name }<br>
   上传文件:${uploadfileForm.myfile }<br>   //直接能够输出去掉上传路径的单独文件名称

 

 

 

抱歉!评论已关闭.