base64编码PNG到Blob

时间:2013-02-03 22:47:27

标签: blob dart

我正在摆弄使用base64编码的PNG创建一个Blob ......

  final FormData formData = new FormData();
  final String base64Image = "data:image/png;base64,iVBORw0K<reduced the data.....>gg==";

  final Blob blob = new Blob([base64Image],"image/png");

  formData.append('file', blob, "android.png");

  req.send(formData);

我不知道我做错了什么,但是blob的内容不是我想要的内容。

事先提前......

[更新

  final FormData formData = new FormData();
  final String base64Image = "iVBORw0KGgo<...reduce data...>kJggg==";

  // BTW: I used the Base64 from dart-sdk/io/base64.dart
  final List<int> intList = Base64.decode(base64Image);
  final Int8Array int8array = new Int8Array.fromList(intList);
  final String atobString = window.atob(base64Image);

  // Does not work
  // final Blob blob = new Blob([atobString]);

  // The same...
  // final Blob blob = new Blob([int8array]);

  formData.append('file', blob, "android.png");
  //formData.append('new-filename', "icon-share.png");

  req.send(formData);

我认为Base64.decode生成的字节数是可以的。文件大小为1003个字节,解码也产生1003个字节。

[更新2 ] 以下是我要说的来源: https://github.com/MikeMitterer/AndroidIconGenerator.DART/blob/master/test/src/restserver.dart

2 个答案:

答案 0 :(得分:0)

在编码为Blob之前,需要解码base64 (即atob)网址。这很简单!试试吧!

答案 1 :(得分:0)

好的,这是我自己问题的答案:

import 'dart:convert'
...

test(' -> Upload File to REST-Server', () {

  final HttpRequest req = new HttpRequest();

  loadEnd(HttpRequest request) {
    if (request.readyState == HttpRequest.DONE) {

      switch(request.status) {

        case HttpStatus.HTTP_200_OK:
          expect(response['path'].endsWith("android.png"),true);

          break;

        case HttpStatus.HTTP_0_COMMUNICATION_FAILED:
          expect(request.status,HttpStatus.HTTP_200_OK);
          break;

        default:
          expect(request.status,HttpStatus.HTTP_200_OK);
          break;
      }
    }
  }

  req.open("POST", uriprovider.forUpload().toString());

  // REST returns JSON Data
  req.setRequestHeader('Accept', 'application/json');

  req.onLoadEnd.listen(expectAsync1((ProgressEvent e) => loadEnd(req)));

  final FormData formData = new FormData();

  final String base64Image = "data:image/png;base64,iVBORw0KG<code reduce for sample>RU5ErkJggg==";
  final String raw = "iVBORw0KG<code reduce for sample>RU5ErkJggg==";
  final String contenttype = "image/png";

  // Base64 is a modified version of dart-sdk/lib/io/base64.dart
  final List<int> intList = BASE64.decode(raw);
  final Int8Array int8array = new Int8Array.fromList(intList);

  // Converting to Uint8Array brought the solution!
  final Uint8Array uint8array = new Uint8Array(intList.length);

  // does not work!
  //var binary = window.atob(raw);

  final Blob blob = new Blob([uint8array]);

  formData.append('file', blob, "android.png");

  req.send(formData);

});

感谢大家把我推向正确的方向!