Pregunta

Can someone please tell me how to create a file and make it available for download via browser button?

I have read about FileWriter but not found any proper example how to use it

and I found a post How to use the dart:html library to write html files?

but the answer just refers to html5lib which just answers how to parse a String to HTML but not how to save as a file.

help appreciated. Am I missing something or there is no example for that usecase??

¿Fue útil?

Solución

Personally, I use a combination of Blob, Url.createObjectUrlFromBlob And AnchorElement (with download and href properties) to create a downloadable file.

Very simple example:

// Assuming your HTML has an empty anchor with ID 'myLink'
var link = querySelector('a#myLink') as AnchorElement;
var myData = [ "Line 1\n", "Line 2\n", "Line 3\n"];
// Plain text type, 'native' line endings
var blob = new Blob(myData, 'text/plain', 'native');
link.download = "file-name-to-save.txt";
link.href = Url.createObjectUrlFromBlob(blob).toString();
link.text = "Download Now!";

Otros consejos

As alluded to by Günter Zöchbauer's comment, an alternative to using Blobs is to base64-encode the data and generate a data URL yourself (at least for file sizes that are well within the data URL limits of most browsers). For example:

import 'dart:html';

Uint8List generateFileContents() { ... }

void main() {
  var bytes = generateFileContents();
  (querySelector('#download-link') as AnchorElement)
    ..text = 'Download File'
    ..href = UriData.fromBytes(bytes).toString()
    ..download = 'filename';
}

Also note that if you do want to use a Blob and want to write binary data from a Uint8List, you are expected to use Blob([bytes], ...) and not Blob(bytes, ...). For example:

  var bytes = generateFileContents();
  var blob = Blob([bytes], 'application/octet-stream');
  (querySelector('#download-link') as AnchorElement)
    ..text = 'Download File'
    ..href = Url.createObjectUrlFromBlob(blob)
    ..download = 'filename';
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top