首页 > 解决方案 > 从 AngularDart 中的输入标签读取文件

问题描述

我正在学习 AngularDart,目前正在尝试使用文件上传按钮读取文件,并在我的模板中使用以下代码。

<input type="file" (change)="onFileChanged($event)">

我的事件处理程序目前采用这种形式,但似乎没有任何效果。使用控制台调试我知道它是文件类型,但是使用诸如 open 和 readAsString 之类的任何方法都会失败。To String 有效,但 onyl 在这种情况下给出了对象的类型,[object File]

import 'dart:io';
import 'dart:html';

import 'package:angular/angular.dart';

// AngularDart info: https://webdev.dartlang.org/angular
// Components info: https://webdev.dartlang.org/components

@Component(
  selector: 'my-app',
  styleUrls: ['app_component.css'],
  templateUrl: 'app_component.html',
  directives: [coreDirectives],
)

class AppComponent {
  String contents;

  onFileChanged(event) {
    contents = event.target.files[0].open(Mode: FileMode.read);
    window.console.debug(contents);
  }
}

感谢帖子中与我的类似问题的帮助,我得到了它的工作。我仍然使用我的事件处理程序并确保我没有同时导入 dart:io 和 dart:html,只需要 dart:html。

这就是我最终的事件处理程序的样子。

import 'dart:html';

import 'package:angular/angular.dart';

@Component(
  selector: 'my-app',
  styleUrls: ['app_component.css'],
  templateUrl: 'app_component.html',
  directives: [coreDirectives],
)

class AppComponent {
  String contents;

  AppComponent();

  void fileUpload(event) {
    InputElement input = window.document.getElementById("fileUpload");
    File file = input.files[0];
    FileReader reader = FileReader();
    reader.readAsText(file);
    reader.onLoad.listen((fileEvent) {
      contents = reader.result;
    });
  }
}

这是我的模板的样子:

<h1>File upload test</h1>
<input type="file" (change)="fileUpload($event)" id="fileUpload">
<div *ngIf="contents != null">
    <p>Hi! These are the contents of your file:</p>
    <p>{{contents}}</p>
</div>

标签: dartangular-dart

解决方案


推荐阅读