Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Created April 23, 2024 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodydavis/d56f1fd3b1a594de47eff13ad904425a to your computer and use it in GitHub Desktop.
Save rodydavis/d56f1fd3b1a594de47eff13ad904425a to your computer and use it in GitHub Desktop.
How to pick a file with package:web
Future<Uint8List?> pickFile() async {
final el = html.document.createElement('input') as html.HTMLInputElement;
el.type = 'file';
el.accept = 'image/*';
el.click();
final completer = Completer<Uri?>();
el.onchange = (html.Event e) {
final files = el.files;
if (files != null && files.length != 0) {
final file = files.item(0);
if (file != null) {
final reader = html.FileReader();
reader.onload = (html.Event _) {
final url = reader.result;
if (url != null) {
completer.complete(Uri.parse(url as String));
} else {
completer.complete(null);
}
}.toJS;
reader.readAsDataURL(file);
} else {
completer.complete(null);
}
} else {
completer.complete(null);
}
}.toJS;
final result = await completer.future;
el.remove();
if (result != null) {
final res = await http.get(result);
if (res.statusCode == 200) {
return res.bodyBytes;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment