介绍
前端页面编码格式和服务端编码格式存在差异,服务器返回blob格式,前端使用非blob格式去解析,会产生乱码。所以在请求接口时一定要设置responseType为blob
导出方法(/src/plugins/download.js)
import axios from 'axios'
import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth'
export default {
downloadFile(url,params,method){
return axios({
method: method,
url: baseURL +url,
responseType: 'blob',
params:params,
headers: { 'Authorization': 'Bearer_' + getToken() }
}).then(async (res) => {
console.log("blob---> ",res);
let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
let objectUrl = URL.createObjectURL(blob);
// window.location.href = objectUrl;
saveAs(objectUrl)
})
},
}
使用
<template>
<div>
<el-button
type="primary"
@click="exportOut"
v-show="routeStatusDc"
class="margin_left_10 searchBtn btn_blur"
:loading="exportLoading"
>导出</el-button
>
</div>
</template>
<script>
export default{
name:"User",
data(){
return{
// 导出遮罩层
exportLoading: false,
routeStatusDc: this.getUserRoles("scglsonrzglsonshxx_export"),
}
},
methods:{
//导出按钮操作
exportOut() {
this.$confirm("是否确认导出所有数据?", "警告", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
}).then(() => {
this.exportLoading = true;
this.$download.downloadFile(
"/bus/order/tongjiShujutongji/export",
"get"
);
this.exportLoading = false;
});
},
}
}
</script>