如何通过Drive API与Flutter访问共享私有文件夹并上传文件
访问Google Drive共享文件夹并上传PDF的解决方案
问题原因
你当前的代码只会搜索当前账号的“我的云端硬盘”,共享给你的私有文件夹不在这个默认搜索范围内,所以无法找到目标文件夹。
解决步骤
1. 修改文件夹查询逻辑,包含共享资源
在files.list的查询条件中加入sharedWithMe = true,明确搜索所有共享给当前账号的资源:
const mimeType = "application/vnd.google-apps.folder"; String folderName = "Shared Folder Name"; final found = await driveApi.files.list( spaces: 'drive', q: "mimeType = '$mimeType' and name = '$folderName' and sharedWithMe = true", $fields: "files(id, name)", ); final files = found.files; if (files == null || files.isEmpty) { return null; } return files.first.id;
2. 特殊情况:共享文件夹在团队盘(Shared Drive)
如果目标共享文件夹属于团队盘,需要额外添加两个参数,确保API可以访问团队盘资源:
const mimeType = "application/vnd.google-apps.folder"; String folderName = "Shared Folder Name"; final found = await driveApi.files.list( spaces: 'drive', q: "mimeType = '$mimeType' and name = '$folderName'", $fields: "files(id, name)", includeItemsFromAllDrives: true, supportsAllDrives: true, ); final files = found.files; if (files == null || files.isEmpty) { return null; } return files.first.id;
3. 验证权限与授权范围
- 确保当前登录账号拥有目标共享文件夹的编辑/写入权限(上传文件需要该权限)
- 确认API授权范围包含
https://www.googleapis.com/auth/drive(或至少https://www.googleapis.com/auth/drive.file,前者权限更全,适合访问共享资源)
4. 上传PDF到共享文件夹
获取到共享文件夹ID后,使用以下代码完成PDF上传:
// 替换为实际的文件路径和共享文件夹ID File pdfFile = File("path/to/your/local/pdf.pdf"); String targetFolderId = "your-shared-folder-id"; String uploadFileName = "uploaded-document.pdf"; // 构建文件元数据,指定父文件夹 var fileMetadata = File() ..name = uploadFileName ..parents = [targetFolderId]; // 构建媒体资源 var media = Media(pdfFile.openRead(), pdfFile.lengthSync()); // 执行上传(如果是团队盘共享,必须加supportsAllDrives: true) final uploadedFile = await driveApi.files.create( fileMetadata, uploadMedia: media, supportsAllDrives: true, ); print("PDF上传成功,文件ID:${uploadedFile.id}");
内容的提问来源于stack exchange,提问作者Abinandhan Selvaraj
相关产品推荐
相关产品推荐

