Downloading a file using Dart GDrive api with authorized GET request

感情迁移 提交于 2019-12-23 02:58:18

问题


I'm coding in Dart and need to download a file (i.e. an image file) from google GDrive using OAuth2.0. I am at the point in my code where I have the downloadURL after having used the Dart drive_v2_api_browser client library.

I tried directly passing this to the "src" attribute

_image = new ImageElement(src: file.downloadUrl, width: file.imageMediaMetadata.width, height: file.imageMediaMetadata.height);
_image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);

but that yielded a 403 forbidden error. That's when I realized I need to make an "authorized GET request". So I tried following the example listed on the Dart Auth pub package https://pub.dartlang.org/packages/google_oauth2_client, but I don't understand what it asking for.

This is what I am trying:

var auth = new oauth.SimpleOAuth2(_picker.Token.data);
var request = new HttpRequest();
request.onLoad.listen(onData_Request, onError: onError_Request, onDone: onDone_Request, cancelOnError: true);
request.open("request", file.downloadUrl);
auth.authenticate(request).then((request) => request.send());

but it keeps giving me an error:

token.... Method request is not allowed by Access-Control-Allow-Methods.

Does anyone have a working example of downloading a file through the Dart GDrive api relative to OAuth2.0?

Update: After Günter Zöchbauer help I was able to continue and convert the blob as such:

Adding this line to the request object:

_downloadRequest.responseType = "blob";

Allowed me to use a file reader:

void onData_Request(Event e) {
  Blob response = _downloadRequest.response;
  final FileReader reader = new FileReader();

  reader.onLoad.listen((e) {
        _handleData(reader);
      });
  reader.readAsArrayBuffer(response);
}

void _handleData(FileReader reader) {
  Uint8List uintlist = new Uint8List.fromList(reader.result);
  String charcodes = new String.fromCharCodes(uintlist);
  _loadImage(_image, charcodes, 225, 225);
}

void _loadImage(ImageElement imageE, String data, int iWidth, int iHeight) {
  _imageAsbase64 = window.btoa(data);

 _image = new ImageElement(src: "data:image/png;base64," + _imageAsbase64, width: iWidth, height: iHeight);
 _image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);
}

void onData(Event e) {
  print("success: ");
  _context.drawImage(_image, 0, 0);
}

回答1:


As the error message says request is not a valid HTTP method. You need something like GET, PUT, POST, DELETE, ...

see also http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html



来源:https://stackoverflow.com/questions/22889356/downloading-a-file-using-dart-gdrive-api-with-authorized-get-request

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