user1199863 user1199863 - 2 months ago 27
Dart Question

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.

Answer

The FileReader API is asynchronous so you need to use event handlers.

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

you also need to allow file uploads from to your browser, which can be done in Chrome by starting it with the flag --allow-file-access-from-files