前言
今天联调文件下载的接口,由于自己用postman测试一直都没问题,但是在和前端联调的时候前端就会出现如下跨域的报错,但是项目是做了统一的跨域处理的,代码类似于下面:文章来源:https://www.toymoban.com/news/detail-801995.html
@ApiOperation("下载附件")
@PostMapping(value = "/download")
public void downloadFile(@RequestBody List<Long> fileId) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletResponse response = servletRequestAttributes.getResponse();
FileBinary fileBinary= fileReportApiClient.download(fileId);
byte[] bytes = fileBinary.getData();
try {
// 清空response
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(new Date().getTime() + ".zip", "utf-8"));
OutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
解决方式
但是项目是做了统一的跨域处理的,后来通过查询资料,发现是response.reset();导致的,正常的respon会带下面的数据,但是.reset()以后会清掉,导致跨域的问题,解决方式,可以通过在reset下添加下列代码,或者将response.reset();删除即可解决。文章来源地址https://www.toymoban.com/news/detail-801995.html
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
到了这里,关于后端使用response.reset()导致出现跨域问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!