Answers:
此方法基于对HTML
文档的操作。应该导入一些其他软件包:
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);
这是DartPad
演示。
通过流行的JS库FileSaver获得了另一种方法
首先,更新您的ProjectFolder/web/index.html
文件以包括该库并定义webSaveAs
函数,如下所示:
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js">
</script>
<script>
function webSaveAs(blob, name) {
saveAs(blob, name);
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
...
然后,您可以从Dart代码中调用此函数,如下所示:
import 'dart:js' as js;
import 'dart:html' as html;
...
js.context.callMethod("webSaveAs", [html.Blob([bytes], "test.txt"])
该解决方案使用FileSaver.js库,应该打开“ saveAs”对话框。
我希望它能按预期工作:
import 'dart:js' as js;
import 'dart:html' as html;
...
final text = 'this is the text file';
final bytes = utf8.encode(text);
final script = html.document.createElement('script') as html.ScriptElement;
script.src = "http://cdn.jsdelivr.net/g/filesaver.js";
html.document.body.nodes.add(script);
// calls the "saveAs" method from the FileSaver.js libray
js.context.callMethod("saveAs", [
html.Blob([bytes]),
"testText.txt", //File Name (optional) defaults to "download"
"text/plain;charset=utf-8" //File Type (optional)
]);
// cleanup
html.document.body.nodes.remove(script);