dartdart-html

How to use the dart:html library to write files?


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


Solution

  • 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!";