The front-end and back-end separate download files are set to cross-domain or No 'Access-Control-Allow-Origin' header is present on the requested resource.

If you set the cross-domain according to the method mentioned on the Internet, but this problem still occurs, then check whether your request header has the attributes as shown in the figure below. If not, then set it directly on the backend

Set response.setHeader("Access-Control-Allow-Origin", "*") directly where it is used ;

@PostMapping("/download/homework")
    public void hwDownload(@RequestBody Map map,HttpServletResponse response) throws Exception {
        String fileName = (String)map.get("fileName");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(LoadUtil.homeworkFolder + File.separator + fileName);
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8")));
            response.setHeader("Content-Length", String.valueOf(fis.getChannel().size()));
            response.setHeader("Access-Control-Allow-Origin", "*");

            byte[] b = new byte[100];
            int len;
            while ((len = fis.read(b)) != -1) {
                response.getOutputStream().write(b, 0, len);
            }
        } catch (IOException e) {
            logger.error("异常:" + e);
        }
        //文件的关闭放在finally中
        finally {
            try {
                response.getOutputStream().flush();
                response.getOutputStream().close();
                fis.close();
            } catch (IOException e) {
                logger.error("异常:" + e);
            }
        }
    }

 

Guess you like

Origin blog.csdn.net/weixin_41786574/article/details/105083009