简体   繁体   English

使用Angular 6上传JSON文件

[英]Upload JSON file using Angular 6

I'm trying to load a JSON file from the user using this method: 我正在尝试使用此方法从用户加载JSON文件:

<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: 这是组件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
  }
}

the line console.log(this.selectedFile); 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). 但是当我尝试使用JSON.stringify打印它的内容时,我得到: {} (空文件)。

What's the cause? 原因是什么?

Thanks. 谢谢。

But when I'm trying to print it's content using JSON.stringify I get: {} (empty file). 但是当我尝试使用JSON.stringify打印它的内容时,我得到:{}(空文件)。

This is not a content of JSON file. 这不是JSON文件的内容。 It's a File object . 这是一个File对象 To read content of JSON you need to use FileReader 要阅读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);
  }
}

JSON.Stringify does not work for File objects in TS/JS. JSON.Stringify不适用于TS / JS中的File对象。 You should extract data from File and then stringify it. 您应该从File中提取数据,然后对其进行字符串化。 For examlple, extract file content as a string or array of strings using https://developer.mozilla.org/en-US/docs/Web/API/FileReader 例如,使用https://developer.mozilla.org/en-US/docs/Web/API/FileReader将文件内容提取为字符串或字符串数​​组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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