vue element 导出blob后台文件流xlsx文件自动下载(且规避乱码)

简介: vue element 导出blob后台文件流xlsx文件自动下载(且规避乱码)

通常情况blob后台文件流都是如下图这样让人崩溃的乱码


<el-button
    type="success"
    @click.stop="handleExport"
    icon="el-icon-download"
>导出</el-button>
// 导出----------------------------------------
handleExport() {
    this.loading = true;
 
    const data = {
        // 导出----------------------------------------
        /*file_name:
            "推广记录(" +
            new Date()
                .toLocaleString("zh-Hans-CN", {
                    year: "numeric",
                    month: "2-digit",
                    day: "2-digit",
                    hour12: false,
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit",
                })
                .replace(/\//g, "-") +
            ").xlsx",*/
        // ----------------------------------------
        gid: this.searchForm.gid,
        gname: this.searchForm.gname,
        type: this.searchForm.type,
        status: this.searchForm.status,
        num: this.searchForm.num,
        hy: this.searchForm.hy,
        remark: this.searchForm.remark,
    };
    this.$axios
        .post(
            "https://xxx.com/getlist?export_flag=1",
            data,
            { responseType: "blob" }
        )
        .then((d) => {
            if (!d.data) return (this.loading = false,this.$message.error(d.msg)); //导出失败报错!
 
            // 自动下载blob文件流xls文件----------------------------------------
            const blob = new Blob([d.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",});//防止下载的文件乱码
            const a= document.createElement("a");
            a.href = URL.createObjectURL(blob);
            a.download=`导出文件(${new Date().toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }).replace(/[\/ :]/g, "")}).xlsx`//后缀名一定要用xlsx,否则会乱码
            ); //设置下载文件名
            a.click();
            //----------------------------------------
 
            this.$message.success("导出xlsx成功");
            this.loading = false;
        });
},
// ----------------------------------------


相关文章
|
1天前
|
JavaScript 前端开发
Vue,如何引入样式文件
Vue,如何引入样式文件
|
1天前
|
JavaScript
|
1天前
|
JavaScript
|
1天前
|
JavaScript
Vue搭配ELEMENT之后,右侧点击栏点击跳转到空白页解决方法
Vue搭配ELEMENT之后,右侧点击栏点击跳转到空白页解决方法
|
1天前
|
JavaScript
vue滚动到页面底部时加载
vue滚动到页面底部时加载
5 1
|
1天前
|
JavaScript 前端开发 API
|
1天前
|
JavaScript 前端开发 网络架构
Vue如何实现页面跳转路由,实现单页面跳转
Vue如何实现页面跳转路由,实现单页面跳转
|
1天前
|
JavaScript
Vue搭配ELEMENT组件,路由不能正确跳转bug
Vue搭配ELEMENT组件,路由不能正确跳转bug
Vue搭配ELEMENT组件,路由不能正确跳转bug
|
1天前
|
JavaScript
vue : 无法将“vue”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保 路径正确,然后再试一次。
vue : 无法将“vue”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保 路径正确,然后再试一次。
|
1天前
|
JavaScript