Springboot 文件下载代码

本文介绍了一种使用JSP实现文件下载的方法,并详细解释了如何从前端处理由后台返回的文件流来实现文件下载。同时,针对具体的技术问题提供了有效的解决方案。

一。JSP 式样的

public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

二。前后端下载代码的逻辑:

如果后台返回的是文件地址,那么前端直接通过 window.location.href 加文件地址,就可以下载文件;

但是如果后台返回的是文件流,那么前端就需要做一些处理;

其实前端处理的核心:就是将文件流转为文件,然后再模拟点击,实现前者的效果。


前端:

const blob = new Blob([res], {
// 设置返回的文件类型
// type: 'application/pdf;charset=UTF-8' 表示下载文档为pdf,如果是word则设置为msword,excel为excel
type: type
})
// 这里就是创建一个a标签,等下用来模拟点击事件
const a = document.createElement('a')
// 兼容webkix浏览器,处理webkit浏览器中href自动添加blob前缀,默认在浏览器打开而不是下载
const URL = window.URL || window.webkitURL
// 根据解析后的blob对象创建URL 对象
const herf = URL.createObjectURL(blob)
// 下载链接
a.href = herf
// 下载文件名,如果后端没有返回,可以自己写a.download = '文件.pdf'
a.download = filename
document.body.appendChild(a)
// 点击a标签,进行下载
a.click()
// 收尾工作,在内存中移除URL 对象
document.body.removeChild(a)
window.URL.revokeObjectURL(herf)
}</pre>


这里用简单的问题:遇到了四个问题:
1.主机被迫连接中断,捕捉异常处理
2.vue 超时处理
3.reset 问题。
4.getOutputStream() has already been called for this response的解决方法,值为空,modelAndView,@ResponseBody都不行

最后的解决方法:

@GetMapping("/t1")
    public void down1(HttpServletResponse response) throws Exception {
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader(
                "Content-disposition",
                "attachment; filename=test.png");
        try(
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\desktop\\1.png"));
                // 输出流
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        ){
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        }
    }

参考资料和推荐阅读:

[1].https://www.jianshu.com/p/a93348d31d8d
[2].https://www.jianshu.com/p/da23cf7c1653
[3].http://www.wjhsh.net/lteal-p-5199911.html
[4].https://wenku.baidu.com/view/d1e44e4b1db91a37f111f18583d049649b660e9c.html?wkts=1669043878887&bdQuery=Springboot+getOutputStream%28%29+has+already+been+called+for+this+response
[5].https://blog.youkuaiyun.com/weixin_43296313/article/details/125100824

spring boot 项目代码,直接启动,第一部分 点睛Spring 4.x 第1 章 Spring 基础 ..........................................2 1.1 Spring 概述 ............................................. 2 1.2 Spring 项目快速搭建 .................................. 5 1.3 Spring 基础配置 .....................................17 第2 章 Spring 常用配置 .... ............................ 30 2.1 Bean 的Scope .... ................................... 30 2.2 Spring EL 和资源调用 .... ...................... 33 2.3 Bean 的初始化和销毁 .... ...................... 37 2.4 Profile .... .... .......... 40 2.5 事件(Application Event) .... .............. 44 第3 章 Spring 高级话题 .... ............................ 48 3.1 Spring Aware .... ..................................... 48 3.2 多线程 .... .... ......... 51 3.3 计划任务 .... .... ..... 54 3.4 条件注解@Conditional .... .................... 56 3.5 组合注解与元注解 .... ........................... 60 3.6 @Enable*注解的工作原理 .... .............. 63 VIII ∣ Java EE 开发的颠覆者:Spring Boot 实战 3.7 测试 .... .... ............. 66 第二部分 点睛Spring MVC 4.x 第4 章 Spring MVC 基础 .... .......................... 72 第三部分 实战Spring Boot 第5 章 Spring Boot 基础 .... ......................... 122 第6 章 Spring Boot 核心 .... ......................... 138 X ∣ Java EE 开发的颠覆者:Spring Boot 实战 第7 章 Spring Boot 的Web 开发 .... ............ 170 7.1 Spring Boot 的Web 开发支持 .... ....... 170 7.2 Thymeleaf 模板引擎 .... ....................... 171 7.2.4 实战 .... ...................................... 177 7.3 Web 相关配置 .... ................................. 182 7.4 Tomcat 配置 .... .................................... 187 7.5 Favicon 配置 .... ................................... 196 7.6 WebSocket .... ....................................... 197 7.7 基于Bootstrap 和AngularJS 的现代Web 应用 .................. 212 第8 章 Spring Boot 的数据访问 .... .............. 233 8.1 引入Docker .... .................................... 237 8.2 Spring Data JPA .... .............................. 248 8.3 Spring Data REST .... ........................... 284 8.4 声名式事务 .... ..................................... 297 8.5 数据缓存Cache .... .............................. 309 8.6 非关系型数据库NoSQL .... ................ 320 8.6.1 MongoDB .... ............................. 320 8.6.2 Redis .... ..................................... 329 第9 章 Spring Boot 企业级开发 .... .............. 340 9.1 安全控制Spring Security .... ............... 340 9.2 批处理Spring Batch .... ....................... 362 9.3 异步消息 .... ......................................... 385 9.4 系统集成Spring Integration .... ........... 395 第10 章 Spring Boot 开发部署与测试 .... ..... 407 第11 章 应用监控 .... ................................... 431 第12 章 分布式系统开发 .... ........................ 456 12.1 微服务、原生云应用 .... ................... 456 12.2 Spring Cloud 快速入门 .... ................. 457 12.3 实战 .... .... ......... 458 12.4 基于Docker 部署 ...................................478
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迅捷的软件产品制作专家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值