從后端接口下載文件的2種方式
一、get方式
直接使用: location.href='http://www.xxx.com/getFile?params1=xxx¶ms2=xxxx'
二、post方式
當有文件需要傳給后端接口、后端處理后返回文件時,用post方式發送formdata。
此時下載后端返回的文件,流程:
1、后端設置Response Headers的2個值:
Content-Disposition:attachment;filename=xxx.xls Content-Type:application/octet-stream
2、前端處理下blob文件:
以vue、vue-resource代碼為例:
Vue.http.post('/xxx/exportDetailData', formData, {responseType: 'blob'}) .then(response => { return response.blob() }) .then(blob => { let url = window.URL.createObjectURL(blob) let link = document.createElement('a') link.download = '詳情數據.xls' link.style.display = 'none' link.href = url document.body.appendChild(link) link.click() URL.revokeObjectURL(link.href) document.body.removeChild(link) }) .catch(error => { console.log(error) })