Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Base64 String to file and view it using Flutter

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??

like image 331
esthrim Avatar asked Oct 02 '18 10:10

esthrim


People also ask

How do you decode a base64 encoded string in flutter?

For base64 decoding, use one of these 2 methods: String base64. encode(List<int> bytes) String base64Encode(List<int> bytes)

How do I get the extension of a base64 string?

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.


1 Answers

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;
 }
like image 190
Ben Avatar answered Oct 11 '22 19:10

Ben