zoukankan      html  css  js  c++  java
  • struts提供下载功能

    1)创建下载页面

    在 struts2Demo06 项目的 WebContent 目录下创建一个名称为 download.jsp 的页面文件,在文件中添加一个用于文件下载的链接,其主要代码如下所示:

    <s:a href="simpledownload?filename=test.txt" name="test">test.txt</s:a>

    2)创建 Action

    在 com.mengma.action 包中新建一个名称为 SimpleDownLoadAction 的类,该类主要用于处理文件下载的核心操作,其代码如下所示。

    package com.mengma.action;
    
    import java.io.InputStream;
    import org.apache.struts2.ServletActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class SimpleDownLoadAction extends ActionSupport {
    private String filename;
    
    public String getFilename() {
      return filename;
    }
    
    public void setFilename(String filename) {
      this.filename = filename;
    }
    
    // 定义了返回InputStream的方法,该方法作为被下载文件的入口
    public InputStream getDownloadFile() {
      // 获取下载文件名称
      String filename = ServletActionContext.getRequest().getParameter(
        "filename");
      // 定义下载文件路径
      String filePath = "/upload/" + filename;
      // 返回一个流对象
      return ServletActionContext.getServletContext().getResourceAsStream(
        filePath);
    }
    
    }

    3)编写配置文件信息

    在 struts.xml 中增加 action 的配置,其代码如下所示:

    <action name="simpledownload" class="com.mengma.action.SimpleDownLoadAction">
        <result type="stream">
            <!--文件类型 -->
            <param name="contentType">text/plain</param>
            <!--指定文件名 -->
            <param name="contentDisposition">
                attachment;filename=${filename}
            </param>
            <!--输入流 -->
            <param name="inputName">downloadFile</param>
        </result>
    </action>

    在上述配置代码中,分别通过 stream 结果类型的属性设置了所要下载文件的类型、名称和输入流。其中 ${filename} 表示在项目运行时,将 action 中的 filename 属性动态地填充在 ${} 中间部分,这样就可以动态地获取所要下载的文件名称。

     

    没有停止的脚步,只有倒下去的脚步
  • 相关阅读:
    XML和解析
    代理模式
    net-snmp配置文件snmp.conf
    tomcat-在eclispe中配置远程调试
    tomcat-在eclipse中配置tomcat容器的内存
    web项目跨域访问
    STS-创建spring配置文件
    STS-新建mvc工程--helloworld
    STS-新建spring mvc项目
    Eclipse-安装Spring Tool Suit 插件
  • 原文地址:https://www.cnblogs.com/hkMblogs/p/13232971.html
Copyright © 2011-2022 走看看