0

I want users to be able to download files uploaded by them. The problem is, certein files (like .pdf) are getting open in the browser, not downloaded. Is there any solution to just download a file in Flutter Web without opening it in the web browser?

Code that I'm using:

final anchor = AnchorElement(
    href: url)
  ..setAttribute("download", fileName)
    ..click();
Henzelix
  • 65
  • 1
  • 10

1 Answers1

0

Following this answer, you can generate url from a string or from a list of int (bytes of file). Here is a short snipper that should work (from the answer above):

import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart


final text = 'this is the text file';

// prepare
final bytes = utf8.encode(text);
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
  ..href = url
  ..style.display = 'none'
  ..download = 'some_name.txt';
html.document.body.children.add(anchor);

// download
anchor.click();

// cleanup
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);

Also, universal_html package is very handy to use html on all Flutter platforms. Using dart:html in a Flutter mobile app will make compiling fail.

Corentin Houdayer
  • 988
  • 2
  • 8
  • 19