简体   繁体   English

如何在Dart中正确下载图片并转换为base64?

[英]How to download picture and convert to base64 correctly in Dart?

I'm in struggle with downloading a picture and then showing it on a page. 我正在努力下载图片然后在页面上显示它。 Printed base64-encoded string looks wrong; 打印base64编码的字符串看起来不对; it's not identical with eg http://www.freeformatter.com/base64-encoder.html result. 它与例如http://www.freeformatter.com/base64-encoder.html结果不同。

This is my code: 这是我的代码:

HttpRequest.request(_url).then((HttpRequest response) {
    String contentType = response.getResponseHeader('Content-Type');

    if (_supportedContentType(contentType)) {
        List bytes = new Utf8Encoder().convert(response.responseText);
        String header = 'data:$contentType;base64,';
        String base64 = CryptoUtils.bytesToBase64(bytes);
        String image = "${header}${base64}";

        me.avatar = image;
        print(image);
    }
}

When you set the responseType you get binary data 设置responseType时,您将获得二进制数据

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.... 数据:图像/ PNG; BASE64,/ 9J / 4AAQSkZJRgABAQEAYABgAAD ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM