Struts上传下载

需要导入两个jar包    commons-fileupload-1.2.2.jar     commons-io-1.4.jar

上传

1 .页面写法

 

   <form action="<%=path %>/stuinfo/uploadImages.action" method="post" enctype="multipart/form-data">
                 <input type="file" name="uploadImage" />
                 <input type="submit" value="上传图片"/>
               </form>

 

 

   2.Action写法

 

/**
     * @author weidan       2013-1-21 上午11:09:33
     * @return
     * remark: 上传图片的action
     */
    public String uploadImages(){
        StuInfo stuInfo = (StuInfo) ActionContext.getContext().getSession().get("user");
        int sid = stuInfo.getSid();
        String dirPath = ServletActionContext.getServletContext().getRealPath("/photo/"+sid);
        if(null!=uploadImage){
            String newFileName = System.currentTimeMillis()+"."+uploadImageFileName.substring(uploadImageFileName.indexOf(".")+1, uploadImageFileName.length());
            File file = new File(dirPath,newFileName);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            uploadImage.renameTo(file);
            //到数据库修改路径
            stuInfoService = new StuInfoImpl();
            stuInfoService.updatePhoto(sid, "/photo/"+sid+"/"+newFileName);
        }
        return "initRes";//上传完图片需要对页面的信息进行初始化
    }

 

 

   3.配置文件写法

     

 <action name="uploadImages" method="uploadImages" class="com.sky.stusource.action.StuInfoAction">
           <result name="initRes" type="chain">initInfo</result>
           <result name="input">/pages/uoloadError.jsp</result>
           <result name="login">/pages/login.jsp</result>
           <interceptor-ref name="defaultStack">
                   <param name="fileUpload.maximumSize">1048576</param>
                   <param name="fileUpload.allowedTypes">image/pjpeg,image/jpeg,image/bmp,image/gif,image/png,image/x-png</param>
           </interceptor-ref>
           <interceptor-ref name="auth"></interceptor-ref>
           <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>

 

 

下载:

Action写法

private String downFileName;

public InputStream getTagFile(){

    return ServletActionContext.getServletContext().getResourceAsStream(downFileName);

}

 

struts.xml的配置

  <action name="download" class="">

        <param name="downFileName" >/img/1.bmp</param>      <!--指定要提供下载的文件-->

        <result>

           <param name="inputName">getTagFile(和Action中的方法对应)</param>

           <param name="contentType">image/bmp</param>要下载的内容

       </result>

  </action>

 

posted @ 2013-01-27 14:11  虎猫  阅读(140)  评论(0编辑  收藏  举报