前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java之struts2之文件下载

java之struts2之文件下载

作者头像
Vincent-yuan
发布2019-09-11 14:44:17
2920
发布2019-09-11 14:44:17
举报
文章被收录于专栏:Vincent-yuanVincent-yuan

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

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

代码语言:javascript
复制
<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实现

代码语言:javascript
复制
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

代码语言:javascript
复制
<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

代码语言:javascript
复制
<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的另一种写法:

代码语言:javascript
复制
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;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档