前言
在開(kāi)發(fā)項(xiàng)目中遇到需要導(dǎo)出列表的功能,一開(kāi)始是前端做的,后來(lái)leader說(shuō)要改成后臺(tái)做,那么辦法就是后臺(tái)返回文件流然后前端執(zhí)行下載。
前端做導(dǎo)出請(qǐng)移步vue-xlsx 導(dǎo)出數(shù)據(jù)公共組件
接受后臺(tái)返回的文件流請(qǐng)接著往下看
后臺(tái)返回來(lái)的數(shù)據(jù)流其實(shí)是二進(jìn)制格式的文件,所以可以用blob接收
第一種方法Blob對(duì)象下載文件流
首先要使用這個(gè)對(duì)象就要先了解這個(gè)對(duì)象,所以,
想了解blob的請(qǐng)移步web-api-blob
api介紹的很詳細(xì),我就不介紹了。
了解完了之后,基本上知道咋回事了,然后直接上代碼,記錄下來(lái)方便以后使,我這里是vue-cli的項(xiàng)目,所以我封裝了公共方法,那個(gè)頁(yè)面使用直接調(diào)用就可以了。
step 一,在公共得js內(nèi)創(chuàng)建自己的方法
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); //創(chuàng)建一個(gè)新的url對(duì)象
link.href = objectUrl;
let file_name = `${moment().format('YYYY-MM-DD HH:mm:ss')}的${list_name}列表.xlsx`;
link.download = file_name; // 下載的時(shí)候自定義的文件名
link.click();
window.URL.revokeObjectURL(objectUrl); //為了更好地性能和內(nèi)存使用狀況,應(yīng)該在適當(dāng)?shù)臅r(shí)候釋放url.
}
step 二,在需要引用引用的頁(yè)面調(diào)用這個(gè)方法就闊以了。
import { moneyFormat, export_excel_file } from "@/utils";
//這個(gè)是封裝好的接口數(shù)據(jù)
import {
withDrawList,
approved,
reject,
admin_withdraw_export,
} from "@/api/finance";
export default {
data(){
return:{}
},
methods:{
export_excel_file,
// 訂單導(dǎo)出
exportOrderList() {
this.listLoading = true;
admin_withdraw_export(this.listQuery)
.then((response) => {
let list_name = "提現(xiàn)";
this.export_excel_file(response, list_name);
this.listLoading = false;
})
.catch(() => {
this.listLoading = false;
this.$message({
message: "導(dǎo)出失敗",
type: "error",
center: true,
duration: "2000",
});
});
},
}
}
重要的提示一定要在自己封裝好的接口中加入
'responseType':"arraybuffer",
這個(gè)參數(shù),否則下載下來(lái)的就是亂碼。
import request from '@/utils/request'
// 提現(xiàn)列表
export function withDrawList(data) {
return request({
url: '/admin/workerWithDraw/admin-page',
method: 'post',
data
})
}
// 提現(xiàn)-導(dǎo)出
export function admin_withdraw_export(data) {
return request({
url: '/admin/workerWithDraw/admin-export',
method: 'post',
data,
'responseType':"arraybuffer",
})
}
正常的axios請(qǐng)求是這樣寫
this.axios.post(baseUrl,Params,{'responseType':"arraybuffer"}).then(response=>{
let list_name = "提現(xiàn)";
this.export_excel_file(response, list_name);
})
第二種方法使用插件js-file-download
下載文件流
step 一,下載安裝這個(gè)插件
npm install js-file-download --save
step 二,在需要引用的頁(yè)面引入,這方法也是需要接口傳入'responseType':"arraybuffer"
參數(shù)
import fileDownload from "js-file-download";
fileDownload(response,'dsdasd.xls');
結(jié)束語(yǔ)
這里做個(gè)筆記,便以后學(xué)習(xí),后期還有學(xué)到的導(dǎo)出的知識(shí)還會(huì)更新。