1

I am trying to load a JSON file from local disk and use the data from it to fill a FabricJS canvas. I have problems on getting the data from the file.

This is what i have till now.

app.html

<input type="file" accept=".json" id="fileInput" (change)="loadFile($event)"/>

app.ts

  loadFile(event) {
const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
const files: FileList = target.files;
this.file = files[0];

const reader = new FileReader();
reader.readAsText(this.file, 'utf8');

this.canvas.loadFromJSON(this.file, this.canvas.renderAll.bind(this.canvas), function (o, object) {
  console.log(o, object);
});

Any thoughts on how I can make this work?

AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
Alex M
  • 17
  • 2

1 Answers1

0

FileReader has an async api.

You must register a callback to the onload event to get the data.

 loadFile(event) {
const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
const files: FileList = target.files;
this.file = files[0];

const reader = new FileReader();
reader.readAsText(this.file, 'utf8');
reader.onload = function() {
  this.canvas.loadFromJSON(reader.result, this.canvas.renderAll.bind(this.canvas), function (o, object) {
  console.log(o, object);
});
}
AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63