通过Google Drive API上传文件时遭遇存储配额错误
问题分析
Service Account本身不具备独立的Google Drive存储配额,这是导致上传失败的核心原因:
- 上传
text/csv格式文件时,文件默认归属Service Account的Drive空间,但它无配额可用,触发「无存储配额」的403错误。 - 转换为
application/vnd.google-apps.spreadsheet格式时,即便目标是你共享给Service Account的个人文件夹,转换操作仍会尝试占用Service Account的配额(其配额为0),因此触发「配额超限」的403错误。
解决方案
1. 配置域范围委派(模拟个人账号操作)
让Service Account以你的个人Google账号身份执行上传,文件将占用你的个人Drive配额,而非Service Account的。操作步骤:
- 登录Google Cloud控制台,进入目标项目 → IAM与管理员 → 域范围委派。
- 启用域范围委派,添加Service Account的客户端ID,并授予
https://www.googleapis.com/auth/drive权限。 - 修改VB.NET认证代码,指定要模拟的个人账号邮箱:
' 替换原认证逻辑 Dim credential As GoogleCredential Dim myScopes As String() = {DriveService.ScopeConstants.Drive} Using fs As New FileStream("credentials2.json", FileMode.Open, FileAccess.Read) credential = GoogleCredential.FromStream(fs) _ .CreateScoped(myScopes) _ .CreateWithUser("你的个人Google账号邮箱") ' 新增模拟用户的代码 End Using Dim uploadService As DriveService = New DriveService(New BaseClientService.Initializer() With { .HttpClientInitializer = credential, .ApplicationName = "Google Drive test"})
修改后上传的文件会归属你的个人账号,可正常存入你共享给Service Account的文件夹。
2. 使用共享驱动器存储
创建共享驱动器并添加Service Account为编辑成员,文件将存储在共享驱动器中,不占用个人或Service Account的配额:
- 在个人Google Drive中创建共享驱动器,进入驱动器设置 → 添加成员,输入Service Account的邮箱(从
credentials2.json的client_email字段获取),设置权限为「编辑」。 - 替换代码中
parentList.Add("FolderIdFromMyDrive")的ID为共享驱动器的ID(从共享驱动器URL的drive/folders/后获取)。 - 保持原有上传逻辑不变,即可完成文件上传。
补充说明
调用DriveService.About.Get()返回StorageQuota.Limit=0是正常结果,因为Service Account确实未分配独立存储配额,多数示例代码未特意提及此细节。
内容的提问来源于stack exchange,提问作者DSW
相关产品推荐
相关产品推荐

