1

我为我的应用程序编写了一个小后端,我可以在其中上传 csv。它需要通过 csv 并将它们解析为 JSON。我为此使用 PapaParse,我可以做一个文件。但是我需要上传多个文件并让它们解析。我可以上传文件,但是我不知道如何选择所有文件。

这是我的代码:HTML

<form class="import">
        <div class="form-group">
            <input type="file" class="form-control-file" id="fileToRead" multiple>
            <small id="fileHelp" class="form-text text-muted">You can enter one day or multiple days. Please see another import for anything other than daily data</small><br>
        </div>
    <!-- this line... the id is in the importData.js file, overflow-y: auto is what makes this section scrollable-->
    <p id="editor" style="border: 1px black dotted; width: 100%; height: 200px; overflow-y: auto;">Hopefully see something here</p>
    </form>

这是js文件:

//Getting the document by the ID and when something changes it runs the function
document.getElementById("fileToRead").addEventListener("change",function(){
    //creates a var for the first file.



 var files = this.file[0]

       Papa.parse(files, {
       header:true,
       dynamictyping:true,
       complete:function(results){
           console.log(results);
           var data = results.split;
           document.getElementById("editor").innerHTML = data;
       }
       });
    //this prints the value of the evt.target.result (which is another pre-defined JS object that runs with
    //FileReader woo hoo!)  this has to have .innerHTML becuase I have a <p> tag, when it was a <textArea> it had
    // to have .value

  });

我很确定它与 JS 中的第一行仅选择文件 0 有关,但是我尝试了空括号和其他一些东西,但它仍然只输出一个对象。

4

1 回答 1

0

好的,所以我想通了。我对如何遍历所有文档感到困惑,这是修复它的代码。

document.getElementById("fileToRead").addEventListener("change",function(){
//creates a var for the first file.
//Gets the number to loop through
var input = document.getElementById("fileToRead");
console.log(input.files.length);
for(var i = 0; i < input.files.length; i++){
    var files = input.files[i];
               Papa.parse(files, {
               header:true,
               dynamictyping:true,
               complete:function(results){
                   console.log(results);
                   document.getElementById("editor").innerHTML = "stuff";
               }
               });

1) 创建一个名为 input 的变量,用于获取所有文件

2)我 console.log 它以便我知道我正在抓取所有文件,您需要将 files.length 添加到输入中,因为您正在查找该输入中的所有文件。文件是我们可以使用的预定义词!

3)然后就像我对 console.log 所做的那样,使用 input.files.length 遍历文件,因为我知道这行得通。我想我本可以创建一个变量,但无论如何。

4) for 循环中的 var 文件与 [i] 一起使用,因为当 for 循环通过时,它将填充 [i] 的值,它以 0 开头,因此它将从第一个文档开始,然后遍历其余部分,直到一个都没有了。

5) 使用 PapaParse 浏览文件。

在竞争:功能(结果)部分,我使用的是 console.log,所以我知道代码在这里。最后一点代码 document.getElementByID 是因为我想看看它输出了什么。这目前不起作用,但它确实输出“我在那里的东西”。

我希望这可以帮助其他人尝试做这样的事情。

于 2016-08-27T14:54:04.783 回答