如何使用 Flutter 访问 Google Drive appdata 文件夹文件?

Dpe*_*nha 2 google-api google-drive-api flutter

我有一个很长一段时间没有接触过的非常古老的 Android 项目。它将一些用户数据存储在用户 Google Drive appdata 文件夹中。现在我正在将应用程序更新为 Flutter 版本,并且由于 Google Drive API 已被弃用,因此 Flutter 没有插件,我相信我现在需要为此使用 googleapi。但是我找不到太多关于我的颤振问题的信息。我到了使用 google_sign_in 登录的地步:^4.0.7

GoogleSignIn _googleSignIn = GoogleSignIn(
    scopes: [
      'email',
      'https://www.googleapis.com/auth/drive.appdata',
      'https://www.googleapis.com/auth/drive.file',
    ],
  );
  try {
    GoogleSignInAccount account = await _googleSignIn.signIn();
  } catch (error) {
    print(error);
  }
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我被困在那里。如何从那里读取用户 Google Drive 上 appdata 文件夹中的文件?

EDIT1:这个答案有帮助,我设法获得了 httpClient,但我仍然坚持如何获得 appdata 文件夹及其文件如何在 Flutter中使用 Google API?

googleapi 似乎不支持 appfolder,因为 Google 可能会在未来弃用它(似乎他们已经这样做了),以迫使我们使用 firebase 支付存储费用。好的,很好,但是如果我无法通过 googleapi 访问该文件夹,我该如何迁移它?如果我现在重置我的应用程序并且我的用户丢失了他们的所有数据,我将丢失我拥有的少数用户......

sur*_*rrz 5

以下对我有用,(使用httpgetpost

身份验证令牌

您可以从 返回的帐户中检索身份验证令牌signIn

Future<String> _getAuthToken() async {
  final account = await sign_in_options.signIn();
  if (account == null) {
    return null;
  }
  final authentication = await account.authentication;
  return authentication.accessToken;
}
Run Code Online (Sandbox Code Playgroud)

搜索

要搜索 AppData 目录中的文件,您需要添加spacesqueryParameters 并将其设置为appDataFolder. 文档在这方面有点误导。

final Map<String, String> queryParameters = {
  'spaces': 'appDataFolder',
  // more query parameters
};
final headers = { 'Authorization': 'Bearer $authToken' };
final uri = Uri.https('www.googleapis.com', '/drive/v3/files', queryParameters);
final response = await get(uri, headers: headers);
Run Code Online (Sandbox Code Playgroud)

上传

要上传文件,您需要为初始上传请求设置正文的parentstoappDataFolder属性。要下载文件,您只需要 fileId。

final headers = { 'Authorization': 'Bearer $authToken' };
final initialQueryParameters = { 'uploadType': 'resumable' };
final Map<String, dynamic> metaData = { 
  'name': fileName,
  'parents': ['appDataFolder ']
};
final initiateUri = Uri.https('www.googleapis.com', '/upload/drive/v3/files', initialQueryParameters);
final initiateResponse = await post(initiateUri, headers: headers, body: json.encode(metaData));
final location = initiateResponse.headers['location'];
Run Code Online (Sandbox Code Playgroud)

下载

要下载文件,您只需要知道fileId,如果您不知道,则需要使用搜索 API 来检索它(见上文)。

final headers = { 'Authorization': 'Bearer $authToken' };
final url = 'https://www.googleapis.com/drive/v3/files/$fileId?alt=media';
final response = await get(url, headers: headers);
Run Code Online (Sandbox Code Playgroud)