1.后端代码(controller)

1.1 controller

@GetMapping("/downloadNodeDeployFile/{nodeId}")
    public void downloadNodeDeployFile(@PathVariable("nodeId") String nodeId, HttpServletResponse response) {
        nodeService.downloadNodeDeployFile(nodeId, response);
    }

1.2 serviceImpl

public void downloadNodeDeployFile(String nodeId, HttpServletResponse response) {
		InputStream deployInputStream = null;
        ServletOutputStream outputStream = null;
        byte[] buf = new byte[1024 * 5];
        try {
            deployInputStream = resourceLoader.getClassLoader().getResourceAsStream("filePath");
            outputStream = response.getOutputStream();
            while (deployInputStream.read(buf) > 0) {
                String s = new String(buf);
                //修改文件信息,动态修改文件
                if (s.contains("test")) {
                    s = s.replace("test", "testtest");
                }
                //去除前后空字符
                s=s.trim();
                //打印下修改后文件
                log.info("修改的文件为:\n {}", s);
                outputStream.write(s.getBytes(), 0, s.length());
            }
            //强制将流刷新到response中
            outputStream.flush();
        } catch (IOException io) {
            log.error("部署文件流传输出错", io);
        } finally {
            try {
                outputStream.close();
                deployInputStream.close();
            } catch (Exception e) {
                log.error("流关闭时出错", e);
            }
        }
    }

2.前端代码(vue3)

const handleDownload =  (activation, nodeId) => {
  axios.get(`your url`,{
    responseType: 'blob',//设置返回类型
    //设置token
    headers: {
      Authorization: store.getters['user/accessToken'],
    },
  },).then((res)=>{
    console.log(res)
    //创建一个a标签元素
    const link=document.createElement('a');
    try {
      //获取到blob
      let blob = new Blob([res.data],{type: "application/octet-stream"});
      console.log(blob);
      let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1];//文件名,中文无法解析的时候会显示 _(下划线),生产环境获取不到
      link.style.display='none';
      // 兼容不同浏览器的URL对象
      const url = window.URL || window.webkitURL || window.moxURL;
      link.href=url.createObjectURL(blob);
      link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_')+1));
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      url.revokeObjectURL(link.href);//销毁url对象
    }catch (e) {
      console.log('下载的文件出错',e)
    }
  }).catch(()=>{

  })
};

3.知识点

3.1 vue中的Bolb

Blob讲解,点此查看

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐