Skip to content

Instantly share code, notes, and snippets.

@lucdotdev
Created February 9, 2021 22:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucdotdev/38b65f5d37fa32eafeb155e6e5224818 to your computer and use it in GitHub Desktop.
Save lucdotdev/38b65f5d37fa32eafeb155e6e5224818 to your computer and use it in GitHub Desktop.
flutter web file picker image, audio
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;
class MyFile {
///@data return a Uint8List of bytes so we can use it in multiparthttp request
final dynamic data;
final String name;
final String dataScheme;
final int type;
const MyFile({
this.dataScheme,
this.data,
this.name,
this.type});
}
//1 for image, 2 for audio
Future<MyFile> filePicker(int type) async {
final html.FileUploadInputElement input = html.FileUploadInputElement();
input..accept = type == 1 ? 'image/*' : 'audio/*';
input.click();
await input.onChange.first;
if (input.files.isEmpty) return null;
final reader = html.FileReader();
reader.readAsDataUrl(input.files[0]);
await reader.onLoad.first;
final encoded = reader.result as String;
final stripped = type == 1
? encoded.replaceFirst(RegExp(r'data:image/[^;]+;base64,'), '')
: encoded.replaceFirst(RegExp(r'data:audio/[^;]+;base64,'), '');
final name = input.files?.first?.name;
return MyFile(data: stripped, dataScheme: encoded, name: name, type: 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment