【问题标题】:Javascript FileReader worked on first try, but not anymore (no line of code has been changed)Javascript FileReader 在第一次尝试时工作,但不再工作(没有更改任何代码行)
【发布时间】:2023-04-03 12:16:01
【问题描述】:

所以我实现了一个 html 输入元素来上传文本文件。然后我想读取文本的内容并将其保存到字符串数组中。为此(我使用的是 Angular 2),我导入了 filereader npm package 以使用 readAsText 函数。现在,当我第一次尝试它时,它起作用了!它打印为文本,从文件中读取到控制台。

然后我删除了 console.log(line) 函数,然后我收到以下错误:“无法读取为文件:{}”。我试图读取 console.log(line) 函数,但我一直收到同样的错误。我在文件读取器使用文件变量之前记录了它,并获得了有关文件的信息。我也尝试了不同的文件,也清除了输入 (el.nativeElement.firstElementChild.value = null),但仍然是同样的错误。

html:

<input hidden="true" type="file" id="fileUpload" (change)="SendSurveyDataToBackend()" [attr.multipleFiles]="multipleFiles ? true : null">

js:

SendSurveyDataToBackend(){
    let inputEl = this.el.nativeElement.firstElementChild; 
    document.getElementById('csvUpload').style.color = "white";
    if (inputEl.files.length == 0 || inputEl.files.length > 1) {
        document.getElementById('csvUpload').style.color = "red";
        return;  
    }

    let file = null;
    file = inputEl.files[0];
    let FileReader = require('filereader');
    const reader = new FileReader();

    let surveyDataSetsAsStrings:string[] = [];        
    let surveyDataSets:SurveyData[] = [];

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.map((line) => {
            surveyDataSetsAsStrings.push(line.toString)
            console.log(line);
        });
    };

    reader.onerror = (evt) => {
        alert(evt.target.error.name);
    };

    reader.readAsText(file);    

    for(var i = 0; i < surveyDataSetsAsStrings.length; i++){
        surveyDataSets[i].Id = parseInt(surveyDataSetsAsStrings[i].substring(0,2));
        surveyDataSets[i].Date = new Date(surveyDataSetsAsStrings[i].substring(42,61));
        surveyDataSets[i].PlayerCode = (surveyDataSetsAsStrings[i].substring(63,73));            
    }
    this.el.nativeElement.firstElementChild.files = null; 
    this.el.nativeElement.firstElementChild.value = null; 

    this.dataService.updateSurveyParticipants(surveyDataSets).subscribe( response => {
        if(response == 'success') // Http OK
            window.location.reload();
        else
        document.getElementById('csvUpload').style.color = "red";
    });   
}

任何想法可能导致这种情况?

【问题讨论】:

    标签: javascript html file file-upload filereader


    【解决方案1】:

    原来我只需要删除以下代码行就可以了...

    let FileReader = require('filereader');
    

    我的错...看起来我确实在它工作后更改了一行代码...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多