zoukankan      html  css  js  c++  java
  • Struts文件下载

    /* 文件下载的先决条件
     * 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>
  • 相关阅读:
    axios baseURL
    TP5 nginx 配置
    Vue
    key
    curl openssl error
    vue use bulma
    《平凡的世界》
    《听听那冷雨》余光中
    心烦意乱
    祝你19岁生日快乐
  • 原文地址:https://www.cnblogs.com/zhang-bo/p/6538837.html
Copyright © 2011-2022 走看看