首页 > 解决方案 > 如何在 JavaScript(本地文件)中一次转换多个文件?

问题描述

我创建了一个转换器,它接收一个 SVG 文件并给我一个文本文件作为输出,并进行了一些修改。如何修改它以应用于一批文件?

我尝试使用 multiple="multiple",但是当我选择输入时,它没有给我选择多个文件的选项。

document.getElementById("fileReader").addEventListener('change', function() {
  var filePath = document.getElementById("fileReader").value;
  var fileName = filePath.substring(filePath.lastIndexOf("\\") + 1, filePath.lastIndexOf("\."));
  var fr = new FileReader();
  fr.onload = function() {;
    var d = new DOMParser().parseFromString(this.result.toString(), "image/svg+xml");
    var textOut = "";
    //various conversion operations.
    function download(filename, text, type = "text/plain") {
      // Create an invisible A element
      const a = document.createElement("a");
      a.style.display = "none";
      document.body.appendChild(a);

      // Set the HREF to a Blob representation of the data to be downloaded
      a.href = window.URL.createObjectURL(
        new Blob([text], {
          type
        })
      );

      // Use download attribute to set set desired file name
      a.setAttribute("download", filename);

      // Trigger the download by simulating click
      a.click();

      // Cleanup
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a);
    }
    // Starting file download.
    document.getElementById("button").onclick = function() {
      download(fileName, textOut);
    };
  }
  fr.readAsText(this.files[0]);
})
<input type="file" id="fileReader" multiple="multiple" />

<input id="button" type="button"/>

哪些更改可以让我一次对多个文件执行此操作?我希望选择的每个文件都被转换并作为单独的文件下载。有没有办法对整个文件夹执行此操作?

标签: javascriptfilesvginputconverters

解决方案


推荐阅读