从后端接口下载文件的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) })