美文网首页
vue中axios使用post请求下载文件中文乱码

vue中axios使用post请求下载文件中文乱码

作者: 臭臭的胡子先生 | 来源:发表于2023-02-27 13:12 被阅读0次

    1、首先我们需要单独封装或者自己在新建axios的时候,需要加上:responseType: "blob", 例如:

    let param = Object.assign({}, this.form, {
            pageIndex: "1",
            pageSize: "1000",
          });
          axios({
            method: "post",
            url:axios.defaults.baseM3URL+ "/find/logs/export",
            responseType: "Blob",
            data: param,
          }).then((res) => {})
    

    2、当前这样做还是远远不够滴,blob的默认编码方式是utf-8,所以就算我们下载下来文档,中文还是乱码的,我们需要将其转换为gbk格式,如何转换呢?在接口请求的出参的最前面加上\ufeff,下面是全部代码仅供参考,亲测有效哦

    startDownload() {
          let param = Object.assign({}, this.form, {
            pageIndex: "1",
            pageSize: "1000",
          });
          axios({
            method: "post",
            url:axios.defaults.baseM3URL+ "/find/logs/export",
            responseType: "Blob",
            data: param,
          }).then((res) => {
            debugger
            let today = new Date();
            let tadayDate =
              today.getFullYear() +
              "-" +
              (today.getMonth() + 1) +
              "-" +
              today.getDate();
            const fileName = "日志查询-" + tadayDate + ".csv";
             let  resdata = "\ufeff" + res.data;
            let blob = new Blob([resdata], { type: 'text/csv,charset=UTF-8'});
            if (window.navigator.msSaveOrOpenBlob) {
              //msSaveOrOpenBlob方法返回bool值
              navigator.msSaveBlob(blob, fileName); //本地保存
            } else {
              var link = document.createElement("a"); //a标签下载
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              window.URL.revokeObjectURL(link.href);
            }
          })
        },
    

    相关文章

      网友评论

          本文标题:vue中axios使用post请求下载文件中文乱码

          本文链接:https://www.haomeiwen.com/subject/ggvhldtx.html