问题记录-全局配置了跨域但是后端下载仍然跨域-(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去了。

相关推荐
Haooog10 分钟前
Agent 开发中的 Memory:State、短期记忆、长期记忆与 Memory Retrieval
java·agent·memory
砚底藏山河17 分钟前
【量化纯GET实战 #23】多股票相关性:用收益率看板块联动
java·数据库·python·金融·数据分析
抠脚小弟32 分钟前
Spring Cache 使用详解:从入门到实战
java·spring
ZGG00342 分钟前
MySQL 索引详解:B+ 树、聚簇索引与最左前缀
java·数据库·mysql
萧瑟余晖1 小时前
Java深入解析篇五十四之对象模型详解
java·开发语言
张文是假的啊1 小时前
Java | record | Controller逻辑
java·开发语言
勿忘,瞬间1 小时前
Mybatis高阶
java·数据库·mybatis
嘻哈baby3 小时前
Go 函数中的参数为什么不支持默认值?
java·开发语言·jvm
慧都小项3 小时前
MyEclipse 2026:当 Agent、MCP 与 Java 26 进入 Eclipse 工作流
java·eclipse·springboot·copilot·myeclipse
CoderYanger3 小时前
前端基础——JavaScript(基础语法)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展