Using Dart to Download a PNG File (Binary File) and displaying it not working

不羁岁月 提交于 2019-12-19 10:22:03

问题


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 !


回答1:


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.



来源:https://stackoverflow.com/questions/18290998/using-dart-to-download-a-png-file-binary-file-and-displaying-it-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!