Home » Javascript » Javascript FileReader worked on first try, but not anymore (no line of code has been changed)

Javascript FileReader worked on first try, but not anymore (no line of code has been changed)

Posted by: admin August 19, 2018 Leave a comment


So I implemented a html input element to upload text files. Then I wanted to read the content of the text and save it to a string array. To do this (I’m using Angular 2) I imported the filereader npm package to use the readAsText function. Now when I tried it for the first time it worked! It printed to text, that was read from the file into the console.

Then I removed the console.log(line) function and since then I get the following error: “cannot read as File: {}”. I tried to readd the console.log(line) function, but I keep getting the same error. I logged the file variable before it is used by the filereader and has the information about the file. I also tried different files and also the clear the input (el.nativeElement.firstElementChild.value = null), but still the same error.


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


    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";

    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) => {

    reader.onerror = (evt) => {


    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
        document.getElementById('csvUpload').style.color = "red";

Any ideas what might be causing this?