I need to download and view file (if possible, for Image, PDF, etc) using Flutter. My problem is, the file that I want to download is Base64 String. How can I achieve that using Flutter??
For base64 decoding, use one of these 2 methods: String base64. encode(List<int> bytes) String base64Encode(List<int> bytes)
To get the extension of an base64 image with JavaScript, we can split the base64 string by the semicolon with split . Then we get the first item from that. And, then we call split again to split the returned string by the / . Then we get the file extension by taking the 2nd element from the returned result.
Following is the code snippet to decode base64 string and save it as a file on the local device. please note in terms of viewing files, image and pdf would require different libraries.
Future<String> _createFileFromString() async {
final encodedStr = "put base64 encoded string here";
Uint8List bytes = base64.decode(encodedStr);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = File(
"$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".pdf");
await file.writeAsBytes(bytes);
return file.path;
}
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