Home > Net >  Read uploaded JSON file in Angular
Read uploaded JSON file in Angular

Time:09-19

I am using the <p-fileUpload> from PrimeNG to upload a json file in my web-app. I want to read the json file, in the front-end, and change some values of a data table.

However, I have no idea how to parse the uploaded file as a json to a typescript object. Any ideas?

In the HTML file:

<p-fileUpload #ratingsUpload mode="basic" name="demo[]"
                    url="" accept=".json"
                    styleClass="p-button-raised"
                    [auto]="true" chooseLabel="Upload ratings"
                    (onUpload)="onRatingsUpload($event)"></p-fileUpload>

In the typescript file:

  onRatingsUpload(event: any) {
    console.log(event.files)
    // TODO:
    // data = JSON(event.files);
  }

Edit: I can't get the event to fire. onRatingsUpload does not seem to be called...

CodePudding user response:

You have to use FileReader:


 const reader = new FileReader();
reader.onload = (event) => {
  try {
    var obj = JSON.parse((event.target.result) as string);
    console.log('my json:', obj);
  } catch (error) {
    console.error(error);
  }
};
reader.readAsText(file);

CodePudding user response:

//You need to use FileReader

onFileChanged(event) {
  this.selectedFile = event.target.files[0];
  const fileReader = new FileReader();
  fileReader.readAsText(this.selectedFile, "UTF-8");
  fileReader.onload = () => {
   console.log(JSON.parse(fileReader.result));
  }
  fileReader.onerror = (error) => {
    console.log(error);
  }
}

  • Related