首页 > 代码库 > Struts12---文件的下载

Struts12---文件的下载

01.创建一个下载的页面  (我们的下载是把文件的路径写成固定的)

  <body>
    <form action="user/download" method="post">
      <input  type="text"  name="download"/>
      <input  type="submit"  value="下载"/>
    </form>
  </body>

 

02.创建对应的struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>

<!--设置开发模式  -->
 <constant name="struts.devMode" value="true"/>
 
    <package name="default"  namespace="/user" extends="struts-default">
       
       <!-- 文件下载  -->
       <action name="download" class="cn.bdqn.action.DownloadAction" method="download">
         <result name="input">/error.jsp</result>
         <result type="stream">
         <!-- ${fileName} 后台获取的fileName -->
          <param name="contentDisposition">attachment;filename=${fileName}</param>
         </result>
       </action>
       
    </package>
</struts>

 

03.创建对应Action

public class DownloadAction extends ActionSupport {
    
     private   String  download; //文件下载的路径
     private   String  fileName; //下载的文件名称
     private  InputStream inputStream; //创建输入流对象
     
     
     //文件下载
     public  String  download(){
         try {
            inputStream=new FileInputStream(download);
            // E:\U1\cat.jpg    只获取文件名
            int index=download.lastIndexOf("\\");
            fileName=download.substring(index+1);
            //防止下载时候中文乱码
            try {
                fileName=URLEncoder.encode(fileName, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return  INPUT;
        }
         
         return SUCCESS;
     }
     
     
     
     
     
     
     
     
     
     
     
    public String getDownload() {
        return download;
    }
    public void setDownload(String download) {
        this.download = download;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
     
    
     
     
     

}

 

Struts12---文件的下载