Javascript 将长字符串编码为 csv 失败

Javascript encoding long string as csv fail

我在 javascript 中有一个方法 returns 一个用逗号分隔的长字符串,然后我需要用那个字符串创建一个 csv 文件,问题是当我有一个长字符串时它什么都不做

这就是我创建文件的方式

let csvContent2 = csv2;
var encoding = "data:text/csv;charset=utf-8,%EF%BB%BF";

link2 = document.createElement("a");
link2.setAttribute("download", filename + "DOC.csv");
link2.setAttribute("href", encoding + encodeURIComponent(csvContent2));

当我尝试触发 link2.click() 并检查 csv 文件时,它什么也没做

使用 URL.createObjectURL

function downloadAsCSV(longCSVString, fileName) {

  const csvBlob = new Blob([longCSVString], {
    type: 'text/csv;charset=utf-8;'
  });

  //for IE11 & Edge
  if (navigator.msSaveBlob) {
    navigator.msSaveBlob(csvBlob, fileName);
  } else {
    //for modern browsers
    const link = document.createElement('a');
    const url = window.URL.createObjectURL(csvBlob);
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
    });
  }
}

// example
downloadAsCSV('YOUR_LONG_CSV_STRING', 'FILE_NAME_HERE');