角度文件下载中断UTF-8 BOM

时间:2019-04-23 06:25:03

标签: angular csv unicode encoding utf-8

我已经用PHP编写了脚本,该脚本用于生成具有UTF-8 BOM编码的CSV文件,并且每当我通过url下载文件时,它都能正常工作,例如: www.example.com/generateCSV

PHP代码:

   $file = tempnam(sys_get_temp_dir(), 'mycsv');
   $df = fopen($file, 'w');
   fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));
   fputcsv($df, ['sd123123123čęėąėąčę', 'ąčęąčęąęąčę'], ';');
   fclose($df);

   header('Content-Type: text/csv; charset=utf-8');
   header('Content-Disposition: attachment; filename=csv.csv');
   header("Cache-Control: no-store, no-cache");
   readfile($file);

但是,当我下载有角度的文件时,我遇到了编码问题。字符不能更有效地识别为UTF-8,并且会中断。 对于csv文件下载,我使用以下角度代码:

t.prototype.downloadCsv = function () {
      var t = this, e = {
        date_from: this.helpers.formatDate(this.filter.date_from),
        date_to: this.helpers.formatDate(this.filter.date_to),
        download: "fees"
      };
      this.http.get("team-accounts/" + this.route.snapshot.params.id, e).subscribe(function (n) {
        var i = {type: "text/csv;charset=utf-8;"},
          r = t.account.team.name + "_summary_" + e.date_from + "_" + e.date_to + ".csv";
        t.helpers.downloadFile(n._body, i, r)
      })
    }

有人看到什么问题了吗? 为什么通过直接链接加载页面效果很好,但是随后我通过角度加载页面却无法正确显示字符?

downloadFile函数:

t.prototype.downloadFile = function (t, e, n, i) {
      var r = new Blob([t], e);
      if (navigator.msSaveBlob) navigator.msSaveBlob(r, n); else {
        var a = document.createElement("a");
        if (void 0 !== a.download) {
          var o = i || document.body, s = URL.createObjectURL(r);
          a.setAttribute("href", s), a.setAttribute("download", n), a.style.visibility = "hidden", o.appendChild(a), a.click(), o.removeChild(a)
        }
      }
    }

0 个答案:

没有答案