简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM