Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload JSON file using Angular 6

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.

like image 397
Philip L Avatar asked Mar 03 '19 16:03

Philip L


1 Answers

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);
  }
}
like image 102
Vadi Avatar answered Nov 05 '22 13:11

Vadi