You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter实现Google Drive文件夹创建、指定上传及文件夹内文件查询

Google Drive API 进阶操作:文件夹创建、指定文件夹上传及文件夹内文件列出

1. 创建Drive文件夹

要创建文件夹,需构造drive.File对象并指定文件夹专属的MIME类型application/vnd.google-apps.folder,调用files.create完成创建:

Future<String?> createDriveFolder(String folderName) async {
  try {
    final client = GoogleAuthClient(authHeaders);
    final ga = drive.DriveApi(client);
    
    final folder = drive.File()
      ..name = folderName
      ..mimeType = 'application/vnd.google-apps.folder';
    
    final createdFolder = await ga.files.create(folder);
    return createdFolder.id;
  } catch (e) {
    logger.e('创建文件夹失败: $e');
    return null;
  }
}

2. 上传文件至指定文件夹

上传时给文件对象添加parents属性,传入目标文件夹ID即可将文件归属到该文件夹下:

Future<void> uploadToDrive(String targetFolderId) async {
  final Directory directory = await getApplicationDocumentsDirectory();
  final File file1 = File('${directory.path}/my_file.txt');
  file1.writeAsStringSync(jsonEncode(context.read<IdeaProvider>().ideaList));

  try {
    final client = GoogleAuthClient(authHeaders);
    final ga = drive.DriveApi(client);
    
    drive.File fileToUpload = drive.File()
      ..name = fileName
      ..parents = [targetFolderId]; // 绑定到目标文件夹

    final response = await ga.files.create(
      fileToUpload,
      uploadMedia: drive.Media(file1.openRead(), file1.lengthSync()),
    );
    logger.wtf('上传文件ID: ${response.id}');
  } catch (e) {
    logger.e('上传文件失败: $e');
  }
}

3. 列出指定文件夹内的文件

调用files.list时通过q参数添加过滤条件,仅获取目标文件夹下的非垃圾文件:

Future<void> _listFilesInFolder(String folderId) async {
  try {
    final client = GoogleAuthClient(authHeaders);
    final ga = drive.DriveApi(client);
    
    // 过滤规则:目标文件夹下、未被删除的文件
    final response = await ga.files.list(
      q: "'$folderId' in parents and trashed=false",
    );

    setState(() {
      // 将response.files赋值给你的列表状态变量
    });

    for (var file in response.files ?? []) {
      print("文件ID: ${file.id} 文件名:${file.name}");
    }
  } catch (e) {
    logger.e('获取文件夹内文件失败: $e');
  }
}

流程调用示例

按创建文件夹→上传文件→列出文件的顺序调用:

// 创建文件夹
final folderId = await createDriveFolder('我的Flutter备份文件夹');
if (folderId != null) {
  // 上传文件到该文件夹
  await uploadToDrive(folderId);
  // 列出文件夹内的文件
  await _listFilesInFolder(folderId);
}

内容的提问来源于stack exchange,提问作者Kavishka Rajapakshe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:30:55