2016-08-27 56 views
1

我为我的应用程序编写了一个小型后端,可以上传csv。它需要经过csv并将其解析为JSON。我正在使用PapaParse,我可以做一个文件。不过,我需要上传多个文件并进行解析。我可以上传文件,但我无法弄清楚如何选择所有文件。使用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但是做我试过空括号和其他一些东西,它仍然只输出一个对象。

回答

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)创建一个名为输入变量,抓住所有

2)我CONSOLE.LOG它让我知道我抓住所有的文件的文件,你需要files.length添加到因为您正在查找该输入中的所有文件。文件是我们可以使用的预先定义的单词!

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

4)for循环中的var文件与[i]一起使用,因为for循环经过它将填充[i]的值,它以0开始,因此它将从第一个文档开始,然后去通过休息,直到没有人离开。

5)使用PapaParse浏览文件。

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

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

相关问题