请求用的axios(类似ajax问题),找了很多方法,都下载不了文件。

 

以下是解决方法):

1.接口返回的流:

 

2、请求头和返回头:

 

 

方法一、方法二:

2.下载流文件的代码

 

方法一:是用了插件 https://github.com/kennethjiang/js-file-download

方法二:是用了 blob

不管哪种方法,记得设置  responseType  !!!!!

 

附上代码:

   //      导出Excel
   exportBill: function () {

     let url_post = Vue.prototype.api.apiList.EXPORT_BILL; //请求地址

     let params_post = { //参数
       orderStartDate: this.timepickerDateFormat(this.rangeTime[0]) || this.rangeTime[0] || '',
       orderEndDate: this.timepickerDateFormat(this.rangeTime[1]) || this.rangeTime[1] || '',
       prodCode: this.prodId,
       promoteFlag: this.promotionSiteId,
       policyStatusList: this.tableBillStateCheckedData,
     };

     Vue.axios.post(url_post, params_post, {
       responseType: 'arraybuffer'
     }).then((res) => {

       let fileName = res.headers['content-disposition'].match(/fushun(\S*)xls/)[0];

       fileDownload(res.data, fileName); //如果用方法一 ,这里需要安装 npm install js-file-download --save ,然后引用 var fileDownload = require('js-file-download'),使用详情见github;
              // let blob = new Blob([res.data], {type: "application/vnd.ms-excel"}); 

              // let objectUrl = URL.createObjectURL(blob); 

              // window.location.href = objectUrl;  

     }).catch(function (res) {});
   },

 

 

 

方法三(附加):

1、接口要求: post方法、入参为json格式、出参文件流

* 2、axios:设置返回数据格式为 blob 或者 arraybuffer   ( 注意 )

   axios({ // 用axios发送post请求
     method: 'post',
     url: ' /serviceTime/exportData', // 请求地址
     data: form, // 参数
     responseType: 'blob', // 表明返回服务器返回的数据类型
     headers: {
       'Content-Type': 'application/json'
     }
   }).then(res => { // 处理返回的文件流
     const blob = new Blob([res.data]);//new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层)
     const fileName = '统计.xlsx';//下载文件名称
     const elink = document.createElement('a');
     elink.download = fileName;
     elink.style.display = 'none';
     elink.href = URL.createObjectURL(blob);
     document.body.appendChild(elink);
     elink.click();
     URL.revokeObjectURL(elink.href); // 释放URL 对象
     document.body.removeChild(elink);
   })

( 上面代码中少取一层的导出文件):

 

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐