【问题标题】:Flutter Web: Downloading file from URL without opening itFlutter Web:从 URL 下载文件而不打开它
【发布时间】:2026-02-13 11:00:01
【问题描述】:

我希望用户能够下载他们上传的文件。问题是,某些文件(如 .pdf)在浏览器中打开,而不是下载。有什么解决方案可以在 Flutter Web 中下载文件而不在 Web 浏览器中打开它?

我正在使用的代码:

final anchor = AnchorElement(
    href: url)
  ..setAttribute("download", fileName)
    ..click();

【问题讨论】:

    标签: file download progressive-web-apps flutter-web


    【解决方案1】:

    this answer 之后,您可以从字符串或int 列表(文件字节)生成url。这是一个应该可以工作的短片(来自上面的答案):

    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);
    

    另外,universal_html 包在所有 Flutter 平台上使用 html 非常方便。在 Flutter 移动应用中使用 dart:html 会导致编译失败。

    【讨论】: