請求用的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
- 1
方法三(附加):
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);
-
})
- 1
( 上面代碼中少取一層的導出文件):
<script>
(function(){
function setArticleH(btnReadmore,posi){
var winH = $(window).height();
var articleBox = $("div.article_content");
var artH = articleBox.height();
if(artH > winH*posi){
articleBox.css({
'height':winH*posi+'px',
'overflow':'hidden'
})
btnReadmore.click(function(){
articleBox.removeAttr("style");
$(this).parent().remove();
})
}else{
btnReadmore.parent().remove();
}
}
var btnReadmore = $("#btn-readmore");
if(btnReadmore.length>0){
if(currentUserName){
setArticleH(btnReadmore,3);
}else{
setArticleH(btnReadmore,1.2);
}
}
})()
</script>
</article>