I want to read a JSON file from the file system but I can't make it work.
I've found this solution that seems to be what I need: Is it possible to upload a JSON file though file upload and read the contents in Angular 6 without talking to an API?
But i get two errors:
Parameter 'event' implicitly has an 'any' type on uploadFile(event) {
and
Object is possibly 'null' on console.log(reader.result.toString());
This is my code:
component.html:
<form name="JSONform" (ngSubmit)="fJSON.form.valid && decryptJSON()" #fJSON="ngForm" novalidate>
<input type="file" name="files" (change)="uploadFile($event)" />
<div >
<div >
<button type="submit">Decrypt</button>
</div>
</div>
</form>
component.ts:
uploadFile(event) {
if (event.target.files.length !== 1) {
console.error('No file selected');
} else {
const reader = new FileReader();
reader.onloadend = (e) => {
console.log(reader.result.toString());
// handle data processing
};
reader.readAsText(event.target.files[0]);
}
}
I don't know what I'm missing. Thank you in advance.
CodePudding user response:
You're not missing anything. These errors are TSLINT or TypeScript errors. Just got to check for them:
// Tell TS that you mean it as any (or you can find the actual event d.ts
// Use the ? operator to check for nulls (or do an if( reader.result != null)
// before calling toString()
uploadFile(event: any) {
if (event.target.files.length !== 1) {
console.error('No file selected');
} else {
const reader = new FileReader();
reader.onloadend = (e) => {
console.log(reader.result?.toString());
// handle data processing
};
reader.readAsText(event.target.files[0]);
}
}