How to download CSV using a href with a # (number sign) in Chrome?

心已入冬 提交于 2019-12-11 18:44:23

问题


Chrome 72+ is now truncating our data at the first sign of a # character.

https://bugs.chromium.org/p/chromium/issues/detail?id=123004#c107

We have been using a temp anchor tag along with the download attribute and href attribute with a csv string to download a csv of data on the page to the user's machines. This is now broken in a recent Chrome update because all data after the first # sign is stripped from the downloaded csv.

We can work around it by replacing the # with " num " or other data, but that leaves our csv/excel files with different data which we'd like to avoid.

Is there any work around we can do to prevent chrome from stripping out the data in the href when downloading the file?

let csvContent = "data:text/csv;charset=utf-8,";
let header = "Col1, Col2, Col3";
csvContent += header + "\r\n";
csvContent += "ac, 123, info here" + "\r\n";
csvContent += "dfe, 432, #2 I break" + "\r\n";
csvContent += "fds, 544, I'm lost due to previous number sign";

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "file.csv");
document.body.appendChild(link);
link.click();

I tried replacing the # with a unicode character of which was close enough, and looked fine in the CSV, but Excel did not like the unicode characters


回答1:


I ran into this same problem, the only change that I did was keeping the "data:text/csv;charset=utf-8," unencoded and just endoding the CSV data portion and use encodeURIComponent instead of encodeURI like so:

let prefix = "data:text/csv;charset=utf-8,";
let header = "Col1, Col2, Col3";
let csvContent = header + "\r\n";
csvContent += "ac, 123, info here" + "\r\n";
csvContent += "dfe, 432, #2 I break" + "\r\n";
csvContent += "fds, 544, I'm lost due to previous number sign";

var encodedUri = prefix + encodeURIComponent(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "file.csv");
document.body.appendChild(link);
link.click();

Copy and paste that into a Chrome console window and it works as expected.



来源:https://stackoverflow.com/questions/55267116/how-to-download-csv-using-a-href-with-a-number-sign-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!