vue通过get方法下载java服务器excel模板

vue通过get方法下载java服务器excel模板

vue方法

handleDownTemplateXls(fileName){
  if(!fileName || typeof fileName != "string"){
    fileName = "导入模板"
  }
  let param = {...this.queryParam};
  if(this.selectedRowKeys && this.selectedRowKeys.length>0){
    param['selections'] = this.selectedRowKeys.join(",")
  }
  console.log("下载模板参数",param)
  downFile(this.url.downTemplateXlsUrl,param).then((data)=>{
    if (!data) {
      this.$message.warning("文件下载失败")
      return
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
    }else{
      let url = window.URL.createObjectURL(new Blob([data]))
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName+'.xls')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
    }
  })
},

java方法

application-dev.yml
#xinhua专用配置
xinhua :
  path :
    #文件上传根目录 设置
    upload: /Users/zhtony/project/xinhua_git/upFiles
    #webapp文件路径
    webapp: /Users/zhtony/project/xinhua_git/webapp
    #导入书籍模板文件
    book: /Users/zhtony/project/xinhua_git/files/导入书籍模板.xls
    #导入学校模板文件
    school: /Users/zhtony/project/xinhua_git/files/导入学校模板.xls

@Value(value = "${xinhua.path.book}")
private String uploadBookPath;

@RequestMapping(value = "/downTemplate")
public void downTemplate(HttpServletRequest request, HttpServletResponse response) {
    try {
        // path是指欲下载的文件的路径。
        File file = new File(uploadBookPath);
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

        // 以流的形式下载文件。
        InputStream fis;
        fis = new BufferedInputStream(new FileInputStream(uploadBookPath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}