zoukankan      html  css  js  c++  java
  • 基于springmvc框架的文件下载功能

    1.访问资源时相应头如果没有设置 Content-Disposition,浏览器默认按 照 inline 值进行处理

               1.1 inline 能显示就显示,不能显示就下载.

    2.只需要修改相应头中 Context-Disposition=”attachment;filename=文 件名”

               2.1 attachment 下载,以附件形式下载.

               2.2 filename=值就是下载时显示的下载文件名

    3.实现步骤

              3.1 导入 apatch 的两个 jar

             3.2 在 jsp 中添加超链接,设置要下载文件

                       3.2.1 在 springmvc 中放行静态资源 files 文件夹

    index.jsp

    <a href="download?fileName=files.rar">下载</a>

    编写控制器方法

    @Controller
    public class DemoController {
        @RequestMapping("download")
        public void download(String fileName,HttpServletResponse res,HttpServletRequest req) throws IOException{
        //设置响应流中文件进行下载
        res.setHeader("Content-Disposition",
        "attachment;filename="+fileName);
        //把二进制流放入到响应体中.
        ServletOutputStream os = res.getOutputStream();
        String path =req.getServletContext().getRealPath("files");
        System.out.println(path);
        File file = new File(path, fileName);
        byte[] bytes =FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
        }
    }


    github中完整的文件下载功能代码:https://github.com/subaojuan/file-download

    github中完整的文件上传功能代码:https://github.com/subaojuan/file-upload

  • 相关阅读:
    ubuntu 安装 Java 开发环境
    mtd-utils 的 使用
    容器技术与虚拟化技术
    Shell之作业控制
    Shell常用语句及结构
    Shell常用命令之read
    Shell之函数
    文件的copy
    类中调用初始化方法
    父类中的方法被覆盖以及子类调用父类覆盖的方法
  • 原文地址:https://www.cnblogs.com/aasu/p/11775015.html
Copyright © 2011-2022 走看看