Created
April 23, 2024 20:06
-
-
Save rodydavis/d56f1fd3b1a594de47eff13ad904425a to your computer and use it in GitHub Desktop.
How to pick a file with package:web
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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