Home > Blockchain >  FileReader() returning undefined and fakepath in Angular
FileReader() returning undefined and fakepath in Angular

Time:07-26

I'm trying to create a form that lets the user upload a csv file, which I will then manipulate using JS and return some arrays of objects. The issue is the upload part.

When I do it in vanilla JS, it works perfectly. But now I'm trying it in Angular and I get the following error:

ERROR TypeError: Cannot read properties of undefined (reading '0')

When I console.log() the pathname of the uploaded file, I get C:\fakepath\fileName.csv. This does not happen when using vanilla JS, so I suspect the issue might be related to that.

Below is my code:

home-page.component.html:

<div >
  <form #myForm id="myForm">
    <div >
      <div >
        <label for="csvFile">Select CSV File</label>
        <input  type="file" accept=".csv" #csvFile />
      </div>
      <div >
        <!-- <button (click)="myClickFunction($event)" class= "btn btn-secondary mt-4" type="submit" value="Submit">Upload</button> -->
        <input (click)="myClickFunction($event)"  type="submit" value="Upload" />
      </div>
    </div>
  </form>
</div>

home-page.comomponent.ts:

import {Component, VERSION, ViewChild, ElementRef, OnInit} from "@angular/core";
import { FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FormBuilder} from '@angular/forms';
import { NgModule} from '@angular/core';

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {

  constructor() {}

  ngOnInit(): void {}

  @ViewChild('csvFile') csvFile!: ElementRef;
  myClickFunction(event: any) {
    event.preventDefault()
    event.stopPropagation()
    console.log(this.csvFile.nativeElement.value);

    const input =this.csvFile.nativeElement.value.files[0];
    const reader = new FileReader();

    console.log("Form submitted "   input);
  }
}

As I mentioned, I suspect the problem might be the fakepath file name, but I can't get sure. I'm very new to Angular so any help will be greatly appreciated! Thank you.

CodePudding user response:

The .value property of the element is a string containing the path/location of your selected file (this says fakepath for security reasons).

So, that property (value) has no field or property called 'files' that is an array, hence the error you are seeing.

You could access the file objects associated to your csvFile input with this.csvFile.nativeElement.files[0]

  • Related