首页 > 解决方案 > Flutter Web 下载文件在移动浏览器中不起作用

问题描述

我正在创建颤振网络,用于下载图像。下载或保存功能仅在 Desktop 中提供。移动浏览器无法下载或保存图像。

这是我的代码:

未来 getWidgetImage() 异步 {

try {
  RenderRepaintBoundary boundary =
      globalKey.currentContext.findRenderObject();
  ui.Image image = await boundary.toImage(pixelRatio: 3.0);
  ByteData byteData =
   await image.toByteData(format: ui.ImageByteFormat.png);
  var pngBytes = byteData.buffer.asUint8List();
  var bs64 = base64Encode(pngBytes);
  debugPrint(bs64.length.toString());
  print("convert done");

  imageList.add(pngBytes);

 if (kIsWeb) {
    websaveAndLaunchFile(bytes, qrName+'.png');
       } 
     else {
     mobilesaveAndLaunchFile(bytes, qrName+'.png');
       }
    return pngBytes;
 } catch (exception) {
  return null;
 }
}

//web保存包

Future <void> websaveAndLaunchFile (List<int> bytes,String fileName)async {
       
    AnchorElement(
    href: "data:application/octet- 
    stream;charset=ut16le;base64,${base64.encode(bytes)}")
    ..setAttribute("Download", fileName)
    ..click();
 }

//mobileSave包

Future<void> mobilesaveAndLaunchFile(List<int> bytes, String fileName)async{

   final path = ( await getExternalStorageDirectory()).path;
   final file = File('$path/$fileName');
   await file.writeAsBytes(bytes, flush: true);
   OpenFile.open('$path/$fileName');
}

标签: javascriptflutterdartflutter-webmobile-browser

解决方案


我建议您使用SaveFile与以下来源相同的 javascript 库:

https://stackoverflow.com/a/60240531/612124


推荐阅读