Vue下载模板文件

有两种方法
1.直接将文件放在public文件夹下
然后在需要下载模板文件的地方定义一个方法,比如

handleDownload() {
    
    
  downloadHandle() {
    
    
      let xhr = new XMLHttpRequest();
      //get后边是public文件夹下需要下载的模板的文件名
      xhr.open("get", `/template2.xlsx`, true)
      xhr.responseType = "blob";
      xhr.onload = function () {
    
    
        if (this.status == 200) {
    
    
          const downloadElement = document.createElement("a");
          const href = window.URL.createObjectURL(this.response);
          downloadElement.href = href;
          //这个也是文件名
          downloadElement.download = "template2.xlsx";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
        }
      };
      xhr.send();
    },

2.将文件放在后端,然后前端调用接口进行下载
比如存放模板文件的接口是/file/downloadExcel,GET请求,参数为res和文件名

  • 我们先在api文件夹下请求一下接口
  getDownloadExcel () {
    
    
    return this.$axios({
    
    
      url: '/file/downloadExcel',
      method: 'GET',
      responseType: 'blob'
    })
  }
  • 然后配置一下请求方法
    handleDownload: function () {
    
    
      FileApi.getDownloadExcel().then((data) => {
    
    
        downloadFile(data, '月份重点工作明细.xls')
      })
    }

猜你喜欢

转载自blog.csdn.net/m0_60429030/article/details/128796530