angular - Angular 文件下载会破坏 UTF-8 BOM
问题描述
我用 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)
})
}
有没有人看到可能是什么问题?为什么通过直接链接加载页面可以正常工作,但是我通过角度加载它会停止正确显示字符?
下载文件功能:
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)
}
}
}
解决方案
推荐阅读
- java - Java - 从 ArrayList 中获取所有元素
- regex - 在 raku 的语法中使用“之后”作为后视
- python - sending a string like "111#013" in python
- java - BiMap with uniqueness along the set (key, value)?
- vb.net - vb.net: BackgroundWorker1_DoWork not working
- c# - 使用计时器递增 ProgressBar
- python - Spyder IDE not displaying inline graphs using Matplotlib
- php - gRPC extension not installed in the right PHP version in Ubuntu 18.04
- java - Setting value to abstract private field from subclass
- c# - to html from c# method