js实现下载内容到excel

115 阅读1分钟
    
    function download(self,url,params,method){
        let config = {
          url: url,
          method: method,
          reponseType:'blob'
        }
        if(method == 'POST'){
          config.data = params;
        }else{
          config.params = params;
        }
        axiosIns(self)(config).then(resp => {
          utils.blobDownload(resp);
        })
    }
    // 二进制下载
    function blobDownload(res){
       const blob = new Blob([res.data],{type:'application/vnd.ms-excel'});
       let fileName = '';
       let disposition = res.headers['content-disposition'];
       if(!disposition){
         disposition = res.headers['Content-Disposition'];
       }
       try{
        disposition = disposition.toLowerCase();
        const result = disposition.match('filename=(.*)');
        if(result){
          fileName = decodeURI(result[1]);
        }
       }catch(error){
        fileName = 'unKnow';
       }
       if('download' in document.createElement('a')){//非IE下载
         const elink = document.createElement('a');
         elink.download = fileName;
         elink.style.display = 'none';
         elink.href = URL.createObjectURL(blob);
         document.body.appendChild(elink);
         elick.click();
         URL.revokeObjectURL(elink.href);//释放URL对象
         document.body.removeChild(elink);
       }else{//IE10+下载
         navigator.msSaveBlob(blob,fileName);
       }
    }

后台返回的内容:

补充知识点:

blog.csdn.net/qq_34752829…