随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

请求处理方法:

复制代码
    @RequestMapping("/download")
    public String download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取下载文件路径
        String realPath = request.getServletContext().getRealPath("/img/img.png");
        // 将文件路径封装为File对象
        File path = new File(realPath);
        // 根据File对象获取文件名
        String fileName = path.getName();
        // 设置响应头:content-disposition 设置文件下载的打开方式,默认在网页上打开
        // 设置attachment;filename= 设置以下载的形式打开文件
        // "UTF-8" 设置编码,以防文件名称中的中文出现乱码
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        InputStream in = new FileInputStream(realPath); // 文件输入流
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while((len = in.read(buffer))>0){
            out.write(buffer,0,len);    // 将缓冲区的数据输出到客户端浏览器
        }
        in.close();
        return null;
    }
复制代码

前端进行下载请求:

访问结果:

点击下载:

 

下载成功 

 

posted on   时间完全不够用啊  阅读(117)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示