Created
February 9, 2021 22:33
-
-
Save lucdotdev/38b65f5d37fa32eafeb155e6e5224818 to your computer and use it in GitHub Desktop.
flutter web file picker image, audio
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
// 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