J.Doe
J.Doe

Reputation: 596

FileReader: get file name

I have a FileReader with an Observable which looks like this:

readDocument(fileChangeEvent: Event) {
    return new Observable<Object>(obs => {
        const file = (fileChangeEvent.target as HTMLInputElement).files[0];
        if (file) {
            const fileReader = new FileReader();
            fileReader.onload = (e) => {
                obs.next(fileReader.result);
            }
            fileReader.readAsText(file);
        }
    });
}

I use the content of the file in the subscription:

this.readDocument(document).subscribe(content => {

}

In the subscription, how could i get the name of the file?

something like this:

   this.readDocument(document).subscribe(content => {
        filename = content.getfilename;
    }

Is this possible? what could be a solution here?

Upvotes: 0

Views: 594

Answers (1)

Norbert Bartko
Norbert Bartko

Reputation: 2632

You can simply return it in the Observable.

readDocument(fileChangeEvent: Event) {
    return new Observable<any>(obs => {
        const file = (fileChangeEvent.target as HTMLInputElement).files[0];
        if (file) {
            const fileReader = new FileReader();
            fileReader.onload = (e) => {
                obs.next({
                   name: file.name,
                   result: fileReader.result,
                });
            }
            fileReader.readAsText(file);
        }
    });
}

Update Here is how i modified you update_chart() and it workz

update_chart(document) {
  this.readDocument(document).subscribe((file: any) => {
    console.log(file.name);
  });
}

Upvotes: 1

Related Questions