Read:
Use this library to select a file: pub.dev/packages/file_picker (Web migration guide)

import 'dart:html' as webFile;
import 'package:file_picker_web/file_picker_web.dart' as webPicker;
 
if (kIsWeb) {
   final webFile.File file = await webPicker.FilePicker.getFile(
      allowedExtensions: ['pd'],
      type: FileType.custom,
   );
  
   final reader = webFile.FileReader();
   reader.readAsText(file);
 
   await reader.onLoad.first;
 
   String data = reader.result;
}

Write (a.k.a download):

import 'dart:html' as webFile;
 
if (kIsWeb) {
   var blob = webFile.Blob(["data"], 'text/plain', 'native');
 
   var anchorElement = webFile.AnchorElement(
      href: webFile.Url.createObjectUrlFromBlob(blob).toString(),
   )..setAttribute("download", "data.txt")..click();
}

原文链接:https://blog.csdn.net/bawomingtian123/article/details/121678099

关于文件下载的重要参考:

import 'dart:html' as html;
void downloadFile(String url) {
   html.AnchorElement anchorElement =  new html.AnchorElement(href: url);
   anchorElement.download = url;
   anchorElement.click();
}

ou can use package url_launcher with url_launcher_web

then you can do:

launchUrl(Uri.parse("data:application/octet-stream;base64,${base64Encode(yourFileBytes)}"));

EDIT: you don’t need a plugin if you do this

download.dart:

import 'dart:convert';
// ignore: avoid_web_libraries_in_flutter
import 'dart:html';

void download(
  List<int> bytes, {
  String downloadName,
}) {
  // Encode our file in base64
  final _base64 = base64Encode(bytes);
  // Create the link with the file
  final anchor =
      AnchorElement(href: 'data:application/octet-stream;base64,$_base64')
        ..target = 'blank';
  // add the name
  if (downloadName != null) {
    anchor.download = downloadName;
  }
  // trigger download
  document.body.append(anchor);
  anchor.click();
  anchor.remove();
  return;
}

empty_download.dart:

void download(
  List<int> bytes, {
  String downloadName,
}) {
  print('I do nothing');
}

import and use:

import 'empty_download.dart'
if (dart.library.html) 'download.dart';

void main () {
  download('I am a test file'.codeUnits, // takes bytes
      downloadName: 'test.txt');
}

https://stackoverflow.com/questions/59783344/flutter-web-download-option

关于在Flutter Web中加载html

https://juejin.cn/post/6844904094725849095

首发:https://www.kkview.com

如果是二进制, 不能直接Blob,需要先转List为Uint8List 才可以(这里是个坑):

dart uint8list to blob
Dart语言中的Uint8List是一种数组,其中的元素都是8位无符号整数。Blob是一种二进制大对象,可以在Web应用程序中存储大量的二进制数据。如果需要将Uint8List转换为Blob,可以使用Dart语言中的Blob类。

以下是代码示例:

import 'dart:typed_data';
import 'dart:html';

void main() {
  Uint8List data = Uint8List.fromList([1, 2, 3, 4]);
  Blob blob = Blob([data], "application/octet-stream");
}

在上面的代码中,我们首先创建了一个Uint8List数组,然后使用它创建了一个Blob对象。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐