Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic (Angular) - Read a file and parse its content

I am working on a project where I want to read content from a file and want to get useful information from its data and display it to user, for example suppose I have a text file (.txt) in which there are 10 lines like "sham went to school", "Rohan bought a new pen" etc. I know this is a silly example but just want to deliver the basic idea. I want to read this content in Ionic and want to show it to user in a beautiful and elegant way after some sort of manipulation. I am using cordova file chooser plugin, now want to read file content as I mentioned above. Any help will be appreciated, Thanks in advance :)

I have tried http get function to read a file but don't know how to use it with choosen file. I made below function and now I have no idea how to pass that file as argument to this function

public readFile(file) {
    this.http.get(file).pipe(map(res => res.text()))                
     .subscribe(data => {                         
      this.requests = data.split('\n');
      this.testtext = this.requests[20];
});
like image 649
Neeraj Sharma Avatar asked Mar 06 '26 18:03

Neeraj Sharma


1 Answers

Here's a file upload function you can use. This uses FileReader. read more

Add this to your component file and use it in template by binding it to an event.

I've added as much comment as I thought would be useful, but let me know if you get confused in any line.

public uploadFile(files: FileList): void {
    let results = [];
    if (files && files.length > 0) {
        const file: File = files.item(0); //assuming only one file is uploaded
        console.log('Uploaded file, Filename:' + file.name + 'Filesize:' + file.size + 'Filetype:' + file.type);
        const reader: FileReader = new FileReader();
        reader.readAsText(file);
        reader.onload = (e) => {
        const fileContent: string = reader.result as string;
        console.log('fileContent:' + fileContent);
        const lines: string[] = fileContent.split('\n'); //this depends on your line end character, I'm using \n in general
        //lines is an array of string, such as "Sham went to school", loop over it and process as you like
        };
    }
}

You can use it in your template, like:

<input type="file" (change)="uploadFile($event.target.files)">
like image 80
Aragorn Avatar answered Mar 08 '26 10:03

Aragorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!