esthrim
esthrim

Reputation: 2130

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

Upvotes: 18

Views: 31783

Answers (2)

mirxtrem apps
mirxtrem apps

Reputation: 67

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();
}

Upvotes: 2

Ben
Ben

Reputation: 343

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;
 }

Upvotes: 33

Related Questions