Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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.com/base64-encoder.html result.

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);
    }
}
like image 411
Cinan Rakosnik Avatar asked Feb 12 '23 10:02

Cinan Rakosnik


1 Answers

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....

like image 112
Günter Zöchbauer Avatar answered Feb 15 '23 00:02

Günter Zöchbauer