2

I have a rest API which I am calling to retrieve a PNG image to display on my page.

My Code:

void getProfilePicture(var pic_id) {

  request = new HttpRequest();
  request.responseType = "blob";
  request.onReadyStateChange.listen(onPicture); 

  // Get Basic Auth credentials
  var authorization = 'Basic '+storage.loginData['password'];

  // Build JSON
  Map reqData = new Map();
  reqData['id'] = pic_id.toString();
  reqData['type'] = 'WEB_SMALL';

  // SEND the request to the server.
  var url = sifted.serverAPI+'/api/v1/pictures/getpicture';
  request.open('POST', url);
  request.withCredentials = false;
  request.setRequestHeader('Authorization',authorization);
  request.setRequestHeader('Content-Type','application/json');
  request.send(json.stringify(reqData));
}

void onPicture(_) {
  if (request.readyState == HttpRequest.DONE &&
      request.status == 200) {
    Blob blob = new Blob(request.response);

    FileReader reader = new FileReader();
    reader.onLoad.listen((fe) { 
      ImageElement imgInput = query('#profilepic');
      imgInput.src = reader.result;
    });
    reader.readAsDataUrl(blob); 
  }  
}

It does not work and I get these errors in the Dart editor:

Exception: type 'Blob' is not a subtype of type 'List' of 'blobParts'.
Exception: type 'Blob' is not a subtype of type 'List' of 'blobParts'.

Any suggestions on what I am doing wrong?

Thank you !

Softinio
  • 638
  • 1
  • 6
  • 19

1 Answers1

3

The problem is this line:

Blob blob = new Blob(request.response);

The Blob constructor expects a List instead of another Blob (which request.response is in your use case): factory Blob(List blobParts, [String type, String endings])

Just delete the line, and directly call reader.readAsDataUrl(request.response), and it should work.

K Walrath
  • 300
  • 3
  • 10
MarioP
  • 3,752
  • 1
  • 23
  • 32
  • Your suggestions worked , but now I want to try to download image synchronously so when I set request.open('POST', url, async: false); it means I can't set request.responseType = "blob"; and now it doesn't work giving error: Exception: type 'String' is not a subtype of type 'Blob' of 'blob'. Any suggestions? Thanks – Softinio Aug 21 '13 at 03:38
  • 1
    @IncitoNetworks Yes. Don't use synchronous HttpRequest for binary data. This might not be what you want to hear, but if major browsers decide they don't want to support this, there isn't much you can do, besides complying. [Or converting the String into a Blob](https://www.google.de/#q=javascript+string+to+blob), which could create a bunch of other problems. – MarioP Aug 21 '13 at 08:44