美文网首页
vue 利用get/post请求实现下载功能

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

作者: Taijia | 来源:发表于2020-12-21 16:53 被阅读0次

一、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
          });
}
`

相关文章

网友评论

      本文标题:vue 利用get/post请求实现下载功能

      本文链接:https://www.haomeiwen.com/subject/qnarnktx.html