10

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.

2 Answers 2

23

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.