码迷,mamicode.com
首页 > 其他好文 > 详细

Struts文件下载

时间:2017-03-12 20:15:51      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:xml配置   返回   download   except   jsp页面   div   text   bsp   ret   

/* 文件下载的先决条件
 * 1. 在xml配置文件中必须配置一个type="stream"的result, result中不需要填写任何内容

* 2. 在Action中编写一个接收文件名的String, 这个变量名必须和JSP页面的参数名完全吻合
* 3. 可以在result中配置一个名为"contentDisposition"的参数, 值是attachment;fileName=${fileName}
* * attachment表示当前下载的内容让浏览器以下载的方式打开 * * ${fileName}表示从对应的Action中获取要下载的文件名, Action中必须提供对应参数的getter方法
*/

1.代码示例:

--->Action类

public class FileDownLoadAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    //文件传过来的名字
    private String fileName;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String execute() throws Exception {
        System.out.println("FileDownLoadAction.execute()");
        if (fileName == null) {
            System.out.println("文件不存在");
        }
        System.out.println(fileName);
        return SUCCESS;
    }
//下载文件的主要业务处理
    public FileInputStream getInputStream() throws Exception {
        //获取到"/FileTransport"的路径
        String path = ServletActionContext.getServletContext().getRealPath("/FileTransport");
        //获取到"/FileTransport"路径下和接受到的文件名一样
        File file = new File(path, fileName);
        //返回获取到的文件
        return new FileInputStream(file);
    }
}

--->filedownload.jsp

<body>
            提交过去的值为文件名相同
<a href="${pageContext.request.contextPath}/filedownload?fileName=index.txt">文件下载</a> </body>

----->配置struts.xml文件

<action name="filedownload"  class="com.gxxy.filetransport.fileupload.FileDownLoadAction">
            <result>/JSP/filetransport/filedownload.jsp</result>
            <result type="stream">
                <param name="contentDisposition">attachment;fileName=${fileName}</param>
            </result>
 </action>

 

Struts文件下载

标签:xml配置   返回   download   except   jsp页面   div   text   bsp   ret   

原文地址:http://www.cnblogs.com/zhang-bo/p/6538837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!