Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File input and Dart

I'm trying out Dart, but I cant figure out, how to send an image from the user to the server. I have my input-tag, and i can reach this in the DART code, but i cant seem to read from it. Im trying something like:

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

With the html containing:

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

I really hope you cant help me, im kinda stuck. I might just be missing how to do the onload for the filereader, or maybe im doing it totally wrong.

like image 669
user1199863 Avatar asked Feb 09 '12 14:02

user1199863


People also ask

How do I write a dart file?

Write to a file To write a string to a file, use the writeAsString method: import 'dart:io'; void main() async { final filename = 'file. txt'; var file = await File(filename). writeAsString('some content'); // Do something with the file. }


2 Answers

My attempt

  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>);
    }
  }
like image 199
Günter Zöchbauer Avatar answered Sep 29 '22 23:09

Günter Zöchbauer


This is how to read a file using 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]);
});
like image 24
stommestack Avatar answered Sep 29 '22 21:09

stommestack