本篇文章記錄如何結合:axios請求後臺實現下載excel文件前端
前端頁面+腳本vue
1 <el-form-item>2 <el-button type="primary" icon="el-icon-search" v-on:click="getList">查詢</el-button>3 </el-form-item>4 <el-form-item>5 <el-button type="primary" icon="el-icon-download" :loading="onDownLoading" v-on:click="DownLoad">下載</el-button>6 </el-form-item>
vue實現:ios
1 var vm = new Vue({ 2 el: '#vm_table', 3 data() { 4 return { 5 onDownLoading: false, //下載中動畫 6 } 7 }, 8 methods: { 9 10 //下載11 async DownLoad() {12 vm.onDownLoading = true; //顯示下載中動態圖13 var param = vm.filter; //參數14 15 //異步下載16 axios.request({17 method: 'post',18 baseURL: this.apiUrl,19 url: '/xxxx/xxxx',20 params: param,21 responseType: 'blob', //接收類型22 }).then(function (res) {23 vm.onDownLoading = false; //關閉下載中動態圖24 if (res.status == 200) {25 let fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]; //excel文件名稱26 let blob = new Blob([res.data])27 if (window.navigator.msSaveOrOpenBlob) {28 navigator.msSaveBlob(blob, fileName);29 } else {30 //非IE下載31 var link = document.createElement('a');32 link.href = window.URL.createObjectURL(blob);33 link.download = fileName;34 link.click();35 window.URL.revokeObjectURL(link.href); //釋放url對象36 }37 } else {38 vm.$message.error('下載失敗,請刷新後從新嘗試');39 }40 }).catch(function (res) {41 vm.onDownLoading = false; //關閉下載中動態圖42 vm.$message.error('請求異常,刷新後從新嘗試');43 })44 },45 46 }47 });
View Code數據庫
服務端實現:axios
1 //下載excel文件 2 [HttpPost] 3 public FileResult DownLoad() 4 { 5 var loginname = Request["loginName"].AsStringWhiteSpace(); 6 var mobile = Request["Mobile"].AsStringWhiteSpace(); 7 try 8 { 9 //查詢數據庫,返回一個DataTable10 DataTable datatabla = RecordsBll.DownLoadRecords(loginname,mobile);11 if (datatabla != null)12 {13 //文件名14 var fileName = DateTime.Now.Ticks.ToString() + ".xlsx";15 if (datatabla.Rows.Count > 50000)16 {17 fileName = DateTime.Now.Ticks.ToString() + ".csv";18 }19 var getbuffer = ExcelHelper.ExportDataTableToExcel(datatabla, true);20 return File(getbuffer, "application/ms-excel".........