說明: 主要是進行下載才使用的. 根據接口設計, 常見的下載方式主要有兩種:
1. get請求
Vue.prototype.$downLoadImg = function(str) { let url = BASE_URL + "/download?path=" + str window.open(url); };
2. post請求, 返回文件流, 需將其轉化為文件.
在vue框架下的使用, 普通情況大同小異.
封裝,可供全局使用:
Vue.prototype.$downloadFile =function(data, fileName){ if (!data) { return } let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', fileName) document.body.appendChild(link) link.click(); link.remove(); };
調用:
downFile () { api.DownLoad(this.checkForm).then(res => { let fileName = 'demo' + formatDate(new Date(),'yyyyMMdd') + '.xlsx' this.$downloadFile(res, fileName); }) },
發送請求時一定要設置responseType: 'blob', 否則轉出的文件將會打不開:
export function DownLoad (data) { var uri = BASE_URL + '/api/downloadList' return fetch({ url: uri, method: 'post', responseType: 'blob', data }); }
其中fetch是二次封裝的axios, BASE_URL是URL變量.