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.
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. }
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>);
}
}
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]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With