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

Google Drive API无报错但文件未上传至关联驱动器问题

Google Drive 文件上传异常排查与解决方案

问题概述

已在Google Cloud Portal完成应用配置(创建OAuth客户端ID与服务账号),使用Postman通过客户端ID测试时可上传文件但文件名未同步;应用中实现上传逻辑后,文件完全未出现在Google Drive中。

上传代码片段

public async Task DriveUploadBasic(string filePath) {
    try {
        // Load pre-authorized user credentials from the environment.
        string keyPath = $"{Directory.GetCurrentDirectory()}\\googleapi1.json";
        GoogleCredential credential = GoogleCredential.FromFile(keyPath)
            .CreateScoped(DriveService.Scope.Drive)
            .CreateScoped(DriveService.Scope.DriveFile);

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer {
            HttpClientInitializer = credential,
            ApplicationName = "TestingApp1"
        });

        //service.HttpClient.Timeout = TimeSpan.FromMinutes(2);

        // Upload file photo.jpg on drive.
        var fileMetadata = new Google.Apis.Drive.v3.Data.File() {
            Name = "test1.csv"
        };
        FilesResource.CreateMediaUpload request;
        // Create a new file on drive.
        using (var stream = new FileStream(filePath, FileMode.Open)) {
            // Create a new file, with metadata and stream.
            request = service.Files.Create(fileMetadata, stream, "text/csv");
            request.Fields = "id";
            var progress = await request.UploadAsync().ConfigureAwait(false);
            if (progress.Status == UploadStatus.Failed) {
                Log($"Upload failed: {progress.Exception}");
            }

            var file = request.ResponseBody;
            //Log(request.ResponseBody.ToString());
            // Prints the uploaded file id.
        }
    }
    catch (Exception e) {
        if (e is AggregateException) {
            Log("Credential Not found");
        }
        else if (e is FileNotFoundException) {
            Log("File not found");
        }
        else {
            Log(e.Message);                    
        }
    }
}

调试信息

  • 服务连接创建成功,无异常抛出
  • 上传文件已被完整读取(共882字节)
  • 请求显示上传完成,所有字节已发送
  • 响应体返回新文件ID,但Google Drive中无对应文件

可能原因

  1. 文件上传至服务账号的私有Drive:服务账号是独立的Google账号,默认上传的文件仅存储在自身Drive中,用户个人Drive无法直接看到
  2. 隐性超时未被捕获:未设置客户端超时,可能存在上传过程中隐性超时导致文件未完成写入
  3. Scope配置冗余:重复调用CreateScoped可能导致权限范围异常
  4. Postman测试的文件名问题:未正确在请求中携带文件元数据(name字段)

解决方案

1. 确认文件是否存在于服务账号Drive

服务账号拥有独立的存储空间,可通过以下方式验证:

  • 在Google Cloud服务账号页面获取服务账号邮箱,结合密钥文件登录Google Drive,检查是否存在上传的文件

2. 给目标用户添加文件访问权限

上传成功后,为个人邮箱添加读写权限,确保文件能在个人Drive中显示:

if (file != null)
{
    var permission = new Google.Apis.Drive.v3.Data.Permission()
    {
        Type = "user",
        Role = "writer",
        EmailAddress = "your-personal-email@example.com" // 替换为你的个人邮箱
    };
    await service.Permissions.Create(permission, file.Id).ExecuteAsync();
    Log($"Uploaded file ID: {file.Id}, permission granted to personal email");
}

3. 优化Scope配置

将重复的CreateScoped调用合并,避免权限范围冲突:

GoogleCredential credential = GoogleCredential.FromFile(keyPath)
    .CreateScoped(new[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile });

4. 启用客户端超时设置

取消注释超时配置,避免隐性超时问题:

service.HttpClient.Timeout = TimeSpan.FromMinutes(2);

5. 完善日志输出

打印文件ID及完整响应,确认上传状态:

var file = request.ResponseBody;
if (file != null)
{
    Log($"Upload completed, file ID: {file.Id}");
}
else
{
    Log("Upload response body is null");
}

6. 修复Postman测试的文件名问题

在Postman的请求中,确保将包含name字段的文件元数据作为JSON体发送,同时附加文件流,避免元数据丢失。

内容的提问来源于stack exchange,提问作者R-Hadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:11:05