【问题标题】:File input and Dart文件输入和 Dart
【发布时间】:2012-03-02 01:08:44
【问题描述】:

我正在尝试 Dart,但我不知道如何将图像从用户发送到服务器。我有我的输入标签,我可以在 DART 代码中找到它,但我似乎无法从中读取。我正在尝试类似:

InputElement ie = document.query('#myinputelement');

ie.on.change.add((event){<br/>
    InputElement iee = document.query('#myinputelement');<br/>
    FileList mfl =  iee.files;<br/>
    File myFile = mlf.item(0);<br/>

    FileReader fr = new FileReader();
    fr.readAsBinaryString(myFile);

    String result = fr.result; //this is always empty
});

html 包含:

<input type="file" id="myinputelement">

我真的希望你不能帮助我,我有点卡住了。我可能只是想念如何为文件阅读器进行加载,或者我做错了。

【问题讨论】:

  • 您是否通过file:// 协议在Chrome 中加载您的页面?如果是这样,您可能需要启用一些标志 stackoverflow.com/a/7691772/180740 - 或上传文件以通过 HTTP 访问它们。

标签: file-upload dart


【解决方案1】:

FileReader API 是异步的,因此您需要使用事件处理程序。

var input = window.document.querySelector('#upload');
Element log = query("#log");

input.addEventListener("change", (e) {
  FileList files = input.files;
  Expect.isTrue(files.length > 0);
  File file = files.item(0);

  FileReader reader = new FileReader();
  reader.onLoad = (fileEvent) {
    print("file read");
    log.innerHTML = "file content is ${reader.result}";
  };
  reader.onerror = (evt) => print("error ${reader.error.code}");
  reader.readAsText(file);
});

您还需要允许从浏览器上传文件,这可以在 Chrome 中通过标记 --allow-file-access-from-files

来完成

【讨论】:

  • 我试图只使用 dart:html atm(你不能同时使用 :/)。使用 dart:html 时,您无法将处理程序添加到文件阅读器。希望你能帮上忙:p
  • 添加了同时使用两个库的示例
【解决方案2】:

没有必要(不再)使用 dart:dom FileReader 而不是来自 dart:html 的那个。

如果您向文件阅读器添加事件侦听器,您的代码应该可以工作,如下所示:

FileReader fr = new FileReader();
fr.on.load.add((fe) => doSomethingToString(fe.target.result));
fr.readAsBinaryString(myFile);

【讨论】:

    【解决方案3】:

    这是使用dart:html读取文件的方法。

    document.querySelector('#myinputelement`).onChange.listen((changeEvent) {
        List fileInput = document.querySelector('#myinputelement').files;
    
        if (fileInput.length > 1) {
            // More than one file got selected somehow, could be a browser bug.
            // Unless the "multiple" attribute is set on the input element, of course
        }
        else if (fileInput.isEmpty) {
            // This could happen if the browser allows emptying an upload field
        }
    
        FileReader reader = new FileReader();
        reader.onLoad.listen((fileEvent) {
              String fileContent = reader.result;
              // Code doing stuff with fileContent goes here!
        });
    
        reader.onError.listen((itWentWrongEvent) {
              // Handle the error
        });
    
        reader.readAsText(fileInput[0]);
    });
    

    【讨论】:

    • The getter 'files' isn't defined for the type 'Element'. Try importing the library that defines 'files', correcting the name to the name of an existing getter, or defining a getter or field named 'files'.dartundefined_getter
    【解决方案4】:

    我的尝试

      void fileSelected(Event event) async {
        final files = (event.target as FileUploadInputElement).files;
        if (files.isNotEmpty) {
          final reader = new FileReader();
    
          // ignore: unawaited_futures
          reader.onError.first.then((evt) => print('error ${reader.error.code}'));
          final resultReceived = reader.onLoad.first;
          reader.readAsArrayBuffer(files.first);
    
          await resultReceived;
          imageReference.fileSelected(reader.result as List<int>);
        }
      }
    

    【讨论】:

      【解决方案5】:

      感谢这篇文章的帮助,我得到了它的工作。我仍然在输入标记中使用我的事件处理程序,并确保我没有同时导入 dart:io 和 dart:html,只需要 dart:html。。 p>

      这就是我最终的 AppComponent 的样子。

      import 'dart:html';
      
      import 'package:angular/angular.dart';
      
      @Component(
        selector: 'my-app',
        styleUrls: ['app_component.css'],
        templateUrl: 'app_component.html',
        directives: [coreDirectives],
      )
      
      class AppComponent {
        // Stores contents of file upon load
        String contents;
      
        AppComponent();
      
        void fileUpload(event) {
          // Get tag and the file 
          InputElement input = window.document.getElementById("fileUpload");
          File file = input.files[0];
      
          // File reader and event handler for end of loading
          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>
      

      【讨论】:

        猜你喜欢
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-18
        相关资源
        最近更新 更多