首页 > 解决方案 > 如何使用 Flutter 访问 Google Drive appdata 文件夹文件?

问题描述

我有一个很老的 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);
  }

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

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

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

标签: fluttergoogle-apigoogle-drive-api

解决方案


以下对我有用,(使用http包 forgetpost

身份验证令牌

您可以从返回的帐户中检索身份验证令牌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;
}

搜索

要在 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);

上传

要上传文件,您需要为初始上传请求设置正文的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'];

下载

要下载文件,您只需要知道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);

推荐阅读