Angular - Read a file and parse its content

You can use FileReader in javascript to achieve this as its a csv file

Add a file change event to store the file in a object as below,

<div class="Block">
  <label id="lbl">Code </label>
  <input type='file' (change)="fileChanged($event)">

</div>

The function should set the file to an object which is used later

file:any;
fileChanged(e) {
    this.file = e.target.files[0];
}

When the submit button is clicked you can use the readAsText() method of FileReader in javascript to get the content as below,

uploadDocument(file) {
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      console.log(fileReader.result);
    }
    fileReader.readAsText(this.file);
}

Note: onload event will be fired after the content is read so your logic should be inside the onLoad function.


you pull the file out of the input and use the FileReader API

readFile(file: File) {
    var reader = new FileReader();
    reader.onload = () => {
        console.log(reader.result);
    };
    reader.readAsText(file);
}

if you want to make it as function you can do

    readFileContent(file: File): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            if (!file) {
                resolve('');
            }

            const reader = new FileReader();

            reader.onload = (e) => {
                const text = reader.result.toString();
                resolve(text);

            };

            reader.readAsText(file);
        });
    }

then

const fileContent = await readFileContent(file);