问题背景
前端请求后端下载文件,其它接口都不会跨域,唯独这个下载跨域了。上代码:
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去了。