1、vue+axios下载文件流

 let that=this;
       that.$ajax({
            url: '地址',
            method: 'get',
            responseType: "blob",  //必须要填写
            headers:{'Content-Type':'application/x-www-form-urlencoded', 'x-locale':'zh-CN'}    
        }).then(function (res) {
              let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
              if (window.navigator.msSaveBlob){
                   window.navigator.msSaveBlob(blob);  
             }else { 
                  let objectUrl = window.URL.createObjectURL(blob); 
                       window.location.href = objectUrl;
            }
         }).catch(function (err) {
                console.log(err)
        })

注意:如果在是封装的axios不生效。只能写在axios({})里面。

2、通过form的方式下载文件流。不过不支持headers里面传递用户信息。只能通过下面的方式传递参数数据。

      var url = "",  data={};
           that.downloadFile( {url:url,  data:data}); 
 downloadFile(options){
          var config = $.extend(true, { method: 'get' }, options);
          var $iframe = $('<iframe id="down-file-iframe" />');
          var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
         $form.attr('action', config.url);
        for (var key in config.data) {
                $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
        }
       $iframe.append($form);
      $(document.body).append($iframe);
      $form[0].submit();
      $iframe.remove();
},

3、下载zip文件

that.$ajax({
        	    	url: '',
        	    	method: 'get',
        	    	responseType: "blob", 
        	    	headers:{'Content-Type':'application/x-www-form-urlencoded', 'x-authorization':store.state.userInfo.sessionId || $uitl.getTokenMsg(), 'x-locale':'zh-CN'}
        	    }).then(function (res) {
        	        let blob = new Blob([res.data], {type: "application/zip"});
        	        if (window.navigator.msSaveBlob){
        	    	    window.navigator.msSaveBlob(blob);  
                    }else { 
                	    let objectUrl = window.URL.createObjectURL(blob); 
                                           window.location.href = objectUrl;
                    }
                }).catch(function (err) {
                    console.log(err)
                }) 
Logo

前往低代码交流专区

更多推荐