问题记录-全局配置了跨域但是后端下载仍然跨域-(Java, SpirngBoot)

问题背景

前端请求后端下载文件,其它接口都不会跨域,唯独这个下载跨域了。上代码:

java 复制代码
@ApiOperation(value = "下载模板文件", notes = "importArchive")
@GetMapping("v1/downLoadTemplate/{templateName}")
public void getTemplate(@PathVariable("templateName") String templateName, HttpServletResponse response) {
    ClassLoader classLoader = getClass().getClassLoader();
    // 罪魁祸首
    response.reset();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + "template" + ".xlsx");
    try (  InputStream fis = classLoader.getResourceAsStream("importer/template/规划成果档案.xlsx");
         OutputStream out = response.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
    } catch (FileNotFoundException e) {
        throw new FileCatalogException.TemplateNotFound(templateName);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

这个代码也是直接从网上粘贴的,结果就遇到坑了,这个故事告诉我们粘贴代码的时候还是要检查一下核心代码干了什么事情。
解决办法:

经过一番搜索,找到了一篇好文,和我的问题一模一样, 参考这篇文章:
https://blog.csdn.net/qq_39999478/article/details/107157324

https://blog.csdn.net/qq_39999478/article/details/107157324

这里也记录一下防止博客失效:

方案一:

java 复制代码
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + "template" + ".xlsx");
response.addHeader("Access-Control-Allow-Origin","*");

方案二:

把这个该死的reset()注释掉

java 复制代码
response.reset();

好了今天的问题记录就到这里,我继续写Bug去了。

相关推荐
xxjj998a4 分钟前
【Spring】Spring MVC案例
java·spring·mvc
阿巴斯甜15 分钟前
Android:MagicIndicator的使用
java
Nyarlathotep011319 分钟前
并发集合类(1):CopyOnWriteArrayList
java·后端
千寻girling22 分钟前
被内推的面试 , 第一次
java·前端·python·面试·职场和发展·typescript·node.js
星辰_mya1 小时前
PV之系统与并发的核心wu器
java·开发语言·后端·学习·面试·架构师
va学弟1 小时前
Agent入门开发
java·运维·服务器·ai
做时间的朋友。1 小时前
Java虚拟线程详解:从原理到实战,解锁百万并发新姿势
java·开发语言
一只大袋鼠1 小时前
MyBatis 从入门到实战(二):代理 Dao 开发与多表关联查询
java·开发语言·数据库·mysql·mybatis
周末也要写八哥1 小时前
C++实际开发之泛型编程(模版编程)
java·开发语言·c++
好家伙VCC1 小时前
**发散创新:用 Rust实现游戏日引擎核心模块——从事件驱动到多线程调度的实战
java·开发语言·python·游戏·rust