基于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

posted @ 2019-04-24 15:47  宝娟  阅读(162)  评论(0编辑  收藏  举报