【问题标题】:How to download picture and convert to base64 correctly in Dart?如何在 Dart 中正确下载图片并转换为 base64?
【发布时间】:2014-09-16 02:57:18
【问题描述】:

我正在努力下载一张图片,然后在页面上显示它。打印的 base64 编码字符串看起来不对;它与例如不同http://www.freeformatter.com/base64-encoder.html 结果。

这是我的代码:

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);
    }
}

【问题讨论】:

  • 有什么问题?你期望print(image) 的输出是什么?
  • 输出以data:image/png;base64,77+977+977+977+9ABBKRklGAAEBAQBgAGAAAO+/ve+/vQBDAAYEB 开头,但应以data:image/png;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAY 开头。为了完整起见,这是文件网址:37.139.24.217/images/…

标签: dart


【解决方案1】:

当你设置 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);
    //}
  });
}

结果:

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

【讨论】:

  • 我有 Dart-sdk 1.5.3 并且没有 asUint8List() 方法。尽管在文档中它存在。
  • 我想还有其他选择可以从ByteBuffer 获得List<int>。我会尝试找到一个,但可能需要一段时间。
  • 我稍微简化了之前的解决方案并添加了另一个解决方案,但我不知道这个解决方案是否适用于 1.5.3。
  • 如何在颤振中做到这一点?
  • @ahmedkhattab 我建议为 Flutter 创建一个新问题,提供有关您的用例的更多详细信息。
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多