首页 > 解决方案 > 使用 Angular 6 上传 JSON 文件

问题描述

我正在尝试使用此方法从用户加载 JSON 文件:

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

这是组件 ts 文件中的代码:

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

该行console.log(this.selectedFile);确实为我提供了文件元数据,即:

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

但是当我试图打印它的内容时,JSON.stringify我得到:({}空文件)。

原因是什么?

谢谢。

标签: javascripthtmljsonangulartypescript

解决方案


但是当我尝试使用 JSON.stringify 打印它的内容时,我得到:{}(空文件)。

这不是JSON文件的内容。它是一个文件对象。要读取 JSON 的内容,您需要使用 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);
  }
}

推荐阅读