dart 如何在Flutter应用程序中使用Google Drive API创建文件夹?

5f0d552i  于 2023-06-19  发布在  Flutter
关注(0)|答案(2)|浏览(164)

我尝试在google drive account中创建flutter app文件夹。它显示了一个bad argument(s) error。虽然我正在使用文档示例
这是我尝试过的代码。它会产生
“错误参数”错误。

final _SCOPES = [drive.DriveApi.DriveScope];

  void adrive(){

clientViaServiceAccount(_credentials,_SCOPES).then(onValue).catchError((e)=>print(e));
  }

  FutureOr onValue(AuthClient client)  {
    //drive.DriveApi(client).files.list().then((value)=>print(value.items[0]));
    // The previous line works fine
    drive.File r = new drive.File();
    r.mimeType = "application/vnd.google-apps.folder";
    r.title = "hello";

    drive.DriveApi(client).files.insert(r,uploadOptions: commons.UploadOptions.Resumable).then((f)=>print(f.mimeType+" "+f.originalFilename))
          .catchError((ex)=>print(ex.toString()));
mlmc2os5

mlmc2os51#

由于您已经完成了Auth credentials,您可以使用此简单函数在Google Drive中创建文件夹。

clientViaServiceAccount(credentials, scopes).then((http_client) async {
              var _drive = v3.DriveApi(http_client);
              var _createFolder = await _drive.files.create(
                v3.File()
                  ..name = 'FileName'
                  ..parents = ['1f4tjhpBJwF5t6FpYvufTljk8Gapbwajc'] // Optional if you want to create subfolder
                  ..mimeType = 'application/vnd.google-apps.folder',  // this defines its folder
              );
            });
o75abkj4

o75abkj42#

我来晚了,但我希望我会为其他谁想要得到文件夹的ID的帮助,这个代码我转换为一个Flutter从Java代码从谷歌官方Google Official Workspace.
首先,你可以创建一个dart类来验证用户:

import 'package:http/http.dart' as http;

class GoogleAuthClient extends http.BaseClient {
  final Map<String, String> _headers;

  final http.Client _client = http.Client();

  GoogleAuthClient(this._headers);

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) {
    return _client.send(request..headers.addAll(_headers));
  }
}

然后创建文件夹函数:

import 'package:YOUR_APP_NAME/google_auth_client.dart';
import 'package:googleapis/drive/v3.dart' as drive;
import 'package:google_sign_in/google_sign_in.dart' as signIn;

  Future<String?> createFolder() async {
    final googleSignIn =
        signIn.GoogleSignIn.standard(scopes: [drive.DriveApi.driveScope]);
    final signIn.GoogleSignInAccount? account = await googleSignIn.signIn();
    final authheader = await account?.authHeaders;

    var client = GoogleAuthClient(authheader!);
    var driveFile = drive.DriveApi(client);

    // File's metadata.
    var fileMetadata = drive.File();
    fileMetadata.name = 'test';
    fileMetadata.mimeType = 'application/vnd.google-apps.folder';

    try {
      var file = await driveFile.files.create(fileMetadata);
      print('Folder ID: ${file.id}');
      return file.id;
    } catch (e) {
      // TODO: Handle error appropriately
      print('Unable to create folder: $e');
      rethrow;
    }
  }

这将创建文件夹,并为您提供文件夹的ID,您将使用该ID将文件上传到该文件夹。

相关问题