前言
在開發項目中遇到需要導出列表的功能,一開始是前端做的,后來leader說要改成后臺做,那么辦法就是后臺返回文件流然后前端執行下載。
前端做導出請移步vue-xlsx 導出數據公共組件
接受后臺返回的文件流請接著往下看
后臺返回來的數據流其實是二進制格式的文件,所以可以用blob接收
第一種方法Blob對象下載文件流
首先要使用這個對象就要先了解這個對象,所以,
想了解blob的請移步web-api-blob
api介紹的很詳細,我就不介紹了。
了解完了之后,基本上知道咋回事了,然后直接上代碼,記錄下來方便以后使,我這里是vue-cli的項目,所以我封裝了公共方法,那個頁面使用直接調用就可以了。
step 一,在公共得js內創建自己的方法
export function export_excel_file(export_data,list_name){
let link = document.createElement("a");
// type就是blob的type,是MIME類型的,可以自己查看MIME類型都有哪些
let blogw = new Blob([export_data],{type:"application/vnd.ms-excel;charset=utf-8"})
let objectUrl = window.URL.createObjectURL(blogw); //創建一個新的url對象
link.href = objectUrl;
let file_name = `${moment().format('YYYY-MM-DD HH:mm:ss')}的${list_name}列表.xlsx`;
link.download = file_name; // 下載的時候自定義的文件名
link.click();
window.URL.revokeObjectURL(objectUrl); //為了更好地性能和內存使用狀況,應該在適當的時候釋放url.
}
step 二,在需要引用引用的頁面調用這個方法就闊以了。
import { moneyFormat, export_excel_file } from "@/utils";
//這個是封裝好的接口數據
import {
withDrawList,
approved,
reject,
admin_withdraw_export,
} from "@/api/finance";
export default {
data(){
return:{}
},
methods:{
export_excel_file,
// 訂單導出
exportOrderList() {
this.listLoading = true;
admin_withdraw_export(this.listQuery)
.then((response) => {
let list_name = "提現";
this.export_excel_file(response, list_name);
this.listLoading = false;
})
.catch(() => {
this.listLoading = false;
this.$message({
message: "導出失敗",
type: "error",
center: true,
duration: "2000",
});
});
},
}
}
重要的提示一定要在自己封裝好的接口中加入
'responseType':"arraybuffer",
這個參數,否則下載下來的就是亂碼。
import request from '@/utils/request'
// 提現列表
export function withDrawList(data) {
return request({
url: '/admin/workerWithDraw/admin-page',
method: 'post',
data
})
}
// 提現-導出
export function admin_withdraw_export(data) {
return request({
url: '/admin/workerWithDraw/admin-export',
method: 'post',
data,
'responseType':"arraybuffer",
})
}
正常的axios請求是這樣寫
this.axios.post(baseUrl,Params,{'responseType':"arraybuffer"}).then(response=>{
let list_name = "提現";
this.export_excel_file(response, list_name);
})
第二種方法使用插件js-file-download
下載文件流
step 一,下載安裝這個插件
npm install js-file-download --save
step 二,在需要引用的頁面引入,這方法也是需要接口傳入'responseType':"arraybuffer"
參數
import fileDownload from "js-file-download";
fileDownload(response,'dsdasd.xls');
結束語
這里做個筆記,便以后學習,后期還有學到的導出的知識還會更新。