himanshu goyal
himanshu goyal

Reputation: 35

angular2 : read a file from local machine

Hi I am new to JavaScript and Angular 2.

I want to read a text file from local machine and show the content on page. I have the file in assets folder. How can I read it using typescript?

Thanks in advance :)

I tried passing file path as "e" but the error i am getting is on files[0]. If I remove files[0] error I am getting is parameter 1 is not of type 'Blob'.

private readSingleFile(e) {
    var fileName = e.files[0];
    console.log(fileName);
    if (!fileName) {
      return;
    }
    var reader = new FileReader();
    reader.onload = file => {
      var contents: any = file.target;
      this.text = contents.result;
    };
    reader.readAsText(fileName);
    console.log(reader.readAsText(fileName))
}

Upvotes: 3

Views: 8330

Answers (2)

himanshu goyal
himanshu goyal

Reputation: 35

Thanks everyone for the responses.

Finally i read the files using 'ng2-file-upload' and uploaded them to server also.

Upvotes: 1

manish kumar
manish kumar

Reputation: 4692

instead of e.files[0]
try

e.target.files[0]

code snippet:

 var fileName = e.target.files[0];

 <input type='file' (change)='readSingleFile($event)'>

Upvotes: 4

Related Questions