15

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

esthrim
  • 1,790
  • 8
  • 28
  • 42
  • 3
    What part is the problem? Import `dart:convert` and use `base64.decode(fileContent)` and show it with `Image.memory`. There are questions about HTTP requests and base 64 already. – Günter Zöchbauer Oct 02 '18 at 11:03
  • @GünterZöchbauer its not only image, it can be pdf, txt, xls and other file types, im still newbie in flutter maybe you can give me example – esthrim Oct 04 '18 at 01:13
  • @esthrim have you solve this so far? – Jose Jet Apr 26 '19 at 19:23

2 Answers2

27

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;
 }
Ben
  • 283
  • 3
  • 5
2

Google Chrome does not let open tab with Url base64 encode, like "data:application/pdf;base64,JVBERi0xLjQKJeLj..." with javascript, so you can not open url with url_launcher, but you can download file.

Here is my code:

import 'dart:html' as html;
...
Future<void> downloadFile() {
  final urlString = "data:application/pdf;base64,JVBERi0xLjQKJeLj...";
  html.AnchorElement anchorElement = html.AnchorElement(href:urlString);
  anchorElement.download = urlString;
  anchorElement.click();
}