Upload JSON file using Angular 6

10,174

But when I'm trying to print it's content using JSON.stringify I get: {} (empty file).

This is not a content of JSON file. It's a File object. To read content of JSON 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);
  }
}
Share:
10,174

Related videos on Youtube

Philip L
Author by

Philip L

Updated on June 04, 2022

Comments

  • Philip L
    Philip L almost 2 years

    I'm trying to load a JSON file from the user using this method:

    <input
      style="display: none"
      type="file" (change)="onFileChanged($event)"
      #fileInput>
    <button (click)="fileInput.click()">Select File</button>
    <button (click)="onUpload()">Upload!</button>
    

    and this is the code in the component ts file:

    export class MyFileUploadComponent {
      selectedFile: File
    
      onFileChanged(event) {
        this.selectedFile = event.target.files[0];
        console.log(this.selectedFile);
        console.log('content: ' + JSON.stringify(this.selectedFile));
      }
    
      onUpload() {
      // upload code goes here
      }
    }
    

    the line console.log(this.selectedFile); does provide me with the file meta data which is:

    lastModified: 1551625969247
    lastModifiedDate: Sun Mar 03 2019 17:12:49 GMT+0200 (Israel Standard Time) {}
    name: "manuscripts.json"
    size: 6008
    type: "application/json"
    webkitRelativePath: ""
    __proto__: File
    

    But when I'm trying to print it's content using JSON.stringify I get: {} (empty file).

    What's the cause?

    Thanks.

  • ammad khan
    ammad khan over 3 years
    Thank you this is exactly what I was looking for.
  • C0mpl3x
    C0mpl3x about 3 years
    How do i format the text after? I get the json in the console correctly but when i want to print it out in html its not formated correctlly