Hi I am new to Angular and currently I am working with Angular 11 project and there I have to upload a CSV file and extract the records of the file in client side and save them in the database via ASP.NET Web API.
Here I followed a tutorial and tried to get the data of the CSV file in angular side and display them in the same page.
Then I got this error,
Type 'File | null' is not assignable to type 'File'. Type 'null' is not assignable to type 'File'.ts(2322)
I tried so many things but still couldn't solve this. Could you please help me?
This is my .ts file,
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styles: [
]
})
export class FileUploadComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
lines: any = [];
linesR: any = [];
changeListener(files: FileList) {
console.log(files);
if (files && files.length > 0) {
let file: File = files.item(0);
console.log(file.name);
console.log(file.size);
console.log(file.type);
let reader: FileReader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
let csv: any = reader.result;
let allTextLines = [];
allTextLines = csv.split(/\r|\n|\r/);
let headers = allTextLines[0].split(';');
let data = headers;
let tarr = [];
for (let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
this.lines.push(tarr);
let tarrR = [];
let arrl = allTextLines.length;
let rows = [];
for (let i = 1; i < arrl; i++) {
rows.push(allTextLines[i].split(';'));
}
for (let j = 0; j < arrl; j++) {
tarrR.push(rows[j]);
}
this.linesR.push(tarrR);
}
}
}
}
This is my .html file
<div class="container">
<h1 style="text-align: center"> File Upload </h1>
<br><br>
<input class="form-control" type="file" class="upload" (change)="changeListener($event.target.files)">
<table class="table table-bordered table-dark">
<thead>
<tr>
<th *ngFor="let item of lines[0]; let i = index">
{{item}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of linesR[0]; let i = index">
<td *ngFor="let itemm of lines[0]; let j = index">
{{item[j]}}
</td>
</tr>
</tbody>
</table>
</div>
Thank you!