Philip L
Philip L

Reputation: 359

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.

Upvotes: 10

Views: 15949

Answers (2)

Vadim
Vadim

Reputation: 3439

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);
  }
}

Upvotes: 23

Daniel Prosianikov
Daniel Prosianikov

Reputation: 118

JSON.Stringify does not work for File objects in TS/JS. You should extract data from File and then stringify it. For examlple, extract file content as a string or array of strings using https://developer.mozilla.org/en-US/docs/Web/API/FileReader

Upvotes: 0

Related Questions