vue 利用get/post请求实现下载功能

一、get请求实现:
1.方法1:

export(){
  window.locaton.href = `${webConfig.calcapi.url}/job/exportdb?ProjectId=${this.projectId}&ProcessId=${this.id}`
}

方法2:
在service.js页面定义好api:

async exportExcel(id) {
    return this.get(`/commonFiles/download/${id}?is_doc=0`, null, {
      responseType: 'arraybuffer'
    });
  }

使用:

exportExcel() {
      ComparisonsService.exportExcel(this.excelFileId).then(res => {
        const aLink = document.createElement('a');
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        aLink.href = URL.createObjectURL(blob);
        aLink.setAttribute(
          'download',
          `Comparisons-Result-${this.excelFileId}.xlsx`
        ); // 设置下载文件名称
        aLink.click();
        // document.body.appendChild(aLink)
        this.$refs.loadElement.appendChild(aLink);
      });
    },

二、post请求实现:
1.在service.js页面定义好api:

async snapshotExport(data) {
    return this.post(`/job/exportdb`, data, {responseType: 'arraybuffer'})
}

2.页面上:

exportZip(){
  let param = {
            projectId: this.projectId,
            processId: this.id,
            templateId: this.templateForm.templateId,
            templateName: this.templateArr.find(
              item => item.id == this.templateForm.templateId
            ).name,
            snapshotId: this.exportId
          };
          this.exportLoading = true
          ProcessService.snapshotExport(param).then(res => {
            const aLink = document.createElement('a');
            const blob = new Blob([res], { type: 'application/zip' });  // 设置下载的格式为zip
            aLink.href = URL.createObjectURL(blob);
            aLink.setAttribute('download', 'download-zip');  // 设置下载文件名称
            aLink.click();
            this.$refs.loadElement.appendChild(aLink);
            this.isShowDialog = false
            this.exportLoading = false
          }).finally(() => {
            this.exportLoading = false
          });
}
`
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容