How to download picture and convert to base64 correctly in Dart?

前端 未结 1 634
离开以前
离开以前 2021-01-06 07:10

I\'m in struggle with downloading a picture and then showing it on a page. Printed base64-encoded string looks wrong; it\'s not identical with e.g. http://www.freeformatter.

1条回答
  •  星月不相逢
    2021-01-06 07:32

    When you set the responseType you get binary data

    import 'dart:html' show HttpRequest;
    import 'dart:convert' show base64;
    import 'dart:typed_data' show Uint8List, ByteBuffer;
    
    main() {
      HttpRequest
          .request("Zacharie_Noterman_-_Monkey_business.jpg",
              responseType: "arraybuffer")
          .then((HttpRequest response) {
        String contentType = response.getResponseHeader('Content-Type');
    
        var list = new Uint8List.view((response.response as ByteBuffer));
    
        String header = 'data:$contentType;base64,';
        String base64 = base64.encode(list);
        String image = "${header}${base64}";
    
        //  me.avatar = image;
        print(image);
        //}
      });
    }
    

    result:

    data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD....

    0 讨论(0)
提交回复
热议问题