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??
Asked
Active
Viewed 2.4k times
15
-
3What 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 Answers
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;
}

Vilash Patel
- 35
- 7

Ben
- 283
- 3
- 5
-
Here, you have a base64 string and create the file. But would you happen to know how to do the inverse, pal? I've an image file path and need to convert it to base64 in a flutter web app for submitting. – Boni Machado Jun 26 '21 at 10:50
-
-
@BoniMachado check this out https://stackoverflow.com/a/50038239/10482516 – Ahmad Khan May 13 '22 at 13:42
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();
}

mirxtrem apps
- 59
- 3