使用Angular 6上传JSON文件 [英] Upload JSON file using Angular 6

查看:104
本文介绍了使用Angular 6上传JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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

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

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

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

But when I'm trying to print it's content using JSON.stringify I get: {} (empty file).

是什么原因?

谢谢.

推荐答案

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

But when I'm trying to print it's content using JSON.stringify I get: {} (empty file).

这不是JSON文件的内容.这是一个文件对象.要读取JSON的内容,您需要使用 FileReader

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

这篇关于使用Angular 6上传JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆