Flutter WEB download option

前端 未结 6 1807
萌比男神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条回答
  •  醉酒成梦
    2021-01-01 16:11

    I've found a solution that let me make an authorized request to get a file (with package http.dart) and then download the file using flutter web (with package dart:html). I don't know if someone other could need this, but I wasn't able to find a solution, so here is the code.

    import 'package:http/http.dart';
    import 'dart:html' as html;
    

    ...

    var headers = {
       'Content-Type': 'application/octet-stream',
       'Accept': 'application/octet-stream',
       'Authorization' : 'Bearer [TOKEN HERE]'
    };
    
    Response res =
          await get(url, headers: headers); 
    
    if (res.statusCode == 200) {
        final blob = html.Blob([res.bodyBytes]);
        final url = html.Url.createObjectUrlFromBlob(blob);
        final anchor = html.document.createElement('a') as html.AnchorElement
          ..href = url
          ..style.display = 'none'
          ..download = filename;
        html.document.body.children.add(anchor);
    
        anchor.click();
    
        html.document.body.children.remove(anchor);
        html.Url.revokeObjectUrl(url);
    }
    

提交回复
热议问题