java之struts2之文件下载

1.在实际应用开发中,文件下载功能也非常常见。

2.最简单的文件下载方式是通过超链接来进行文件下载:

<body>
    <a href="download/s.txt">课件</a><br/>
    <a href="download/t.jpg">美女</a><br/>
    <a href="download/jstl-1.2.jar">jstl</a>
</body>

注意:直接通过超链接下载文件,如果浏览器能够读取文件,浏览器会直接读取,而不会下载到本地。并且有安全问题。所以,可以通过action来实现下载。

3.Struts2文件下载功能的实现:

Action实现

复制代码
public class DownloadAction {
    private String fileName;
    public String execute(){
        return Action.SUCCESS;
    }
    //获取文件流
    public InputStream getInputStream() throws FileNotFoundException{
        String path=ServletActionContext.getServletContext().getRealPath("/download");
        return new FileInputStream(new File(path,fileName));
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
复制代码

Struts.xml

复制代码
<package name="default" extends="struts-default" namespace="/">
        <action name="download" class="cn.sxt.action.DownloadAction">
            <result type="stream">
                <!-- 根据inputName生产的get方法  到Action中去取得该方法的返回值 -->
                <param name="inputName">inputStream</param>
                <!-- 设置下载的文件 直接保存 -->
                <param name="contentDisposition">attachment;filename=${fileName}</param>
            </result>
        </action>
    </package>
复制代码

jsp

<body>
        <a href="download/2.txt">课件</a> <br />
        <a href="download/1.jpg">美女</a> <br />
        <hr />
        <a href="download.action?fileName=2.txt">课件</a> <br />
        <a href="download.action?fileName=1.jpg">美女</a> <br />
  </body>

 

或者 Action的另一种写法:

复制代码
public class DownloadAction {
    private String fileName;
    private InputStream inputStream;
    public String execute() throws FileNotFoundException{
        String path=ServletActionContext.getServletContext().getRealPath("/download");
        inputStream =  new FileInputStream(new File(path,fileName));
        return Action.SUCCESS;
    }
    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}
复制代码
posted @   Vincent-yuan  阅读(2208)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示