如何在Flutter Web应用程序中保存和下载文本文件


9

我是Flutter的新手,正在Flutter的Web应用程序中工作。我的要求是创建和下载文本文件。像下面

void getData() {
    List<int> bytes = utf8.encode('this is the text file');
    print(bytes); // Need to download this with txt file.
}

谁能帮我实现这一目标

Answers:


12

此方法基于对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演示。


谢谢!感觉有点hacky,但是可以用。不幸的是,我没有在Chrome中看到“另存为”对话框,它只是开始下载文件。而且我的“在下载之前先询问在哪里保存每个文件”设置已打开。
Oleksii Shliama

@OleksiiShliama如果您查看FileSaver.js库,它实际上在做与Spatz完全相同的事情:)。在这里检查。另外,“另存为”对话框会以chrome的形式显示给我。可能是版本问题。
Abhilash Chandran

8

通过流行的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"])

0

该解决方案使用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);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.