Flutter WEB download option

前端 未结 6 1790
萌比男神i
萌比男神i 2021-01-01 15:43

I am making flutter web app that should generate a file from user data. And have the option to download the output file.

But I can not find any options/packages whic

6条回答
  •  萌比男神i
    2021-01-01 16:09

    you can use package url_launcher with url_launcher_web

    then you can do:

    launch("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 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 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');
    }
    

提交回复
热议问题