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

如何使用C#在ASP.NET Core MVC应用中无需登录直接上传文件到Google Drive

实现方案:ASP.NET Core MVC无人工登录上传文件到Google Drive

完全可以实现,核心采用Google Cloud的**服务账号(Service Account)**鉴权方案,无需人工交互登录,全程服务端即可完成鉴权和上传操作。


核心逻辑

服务账号是属于应用程序的独立身份账号,不需要绑定个人用户,通过密钥文件即可完成身份验证,适配服务端后台自动上传的场景。


前置准备

  • 在Google Cloud Console创建项目,开启Google Drive API权限
  • 创建服务账号,下载JSON格式的密钥文件,保存到ASP.NET Core项目的安全路径下,禁止提交到公共代码仓库
  • 把你要上传的目标Google Drive文件夹的编辑权限,分享给服务账号的关联邮箱(可在服务账号详情页查看,格式为xxx@xxx.iam.gserviceaccount.com,否则服务账号无权限写入你的Drive空间)

代码实现

第一步:安装依赖NuGet包

Install-Package Google.Apis.Drive.v3
Install-Package Google.Apis.Auth

第二步:编写上传逻辑

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Microsoft.AspNetCore.Mvc;
using System.IO;

public class GoogleDriveController : Controller
{
    private readonly DriveService _driveService;

    public GoogleDriveController()
    {
        // 替换为你的服务账号密钥文件实际路径
        var credentialPath = "service-account-key.json";
        GoogleCredential credential;
        
        using (var stream = new FileStream(credentialPath, FileMode.Open, FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(DriveService.Scope.Drive);
        }

        // 初始化Google Drive服务实例
        _driveService = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "你的应用名称"
        });
    }

    /// <summary>
    /// 上传文件到Google Drive接口
    /// </summary>
    [HttpPost]
    public IActionResult UploadFile(IFormFile uploadFile)
    {
        if (uploadFile == null || uploadFile.Length == 0) 
            return BadRequest("上传文件不能为空");

        // 配置文件元数据
        var fileMetadata = new Google.Apis.Drive.v3.Data.File()
        {
            Name = uploadFile.FileName,
            // 替换为你的目标文件夹ID,从Drive网页端文件夹URL末尾获取
            Parents = new List<string> { "目标文件夹ID" }
        };

        using (var stream = uploadFile.OpenReadStream())
        {
            var uploadRequest = _driveService.Files.Create(fileMetadata, stream, uploadFile.ContentType);
            uploadRequest.Fields = "id, name";
            // 如果上传到共享盘需要加这行
            // uploadRequest.SupportsAllDrives = true;
            
            var uploadResult = uploadRequest.Upload();

            if (uploadResult.Status == Google.Apis.Upload.UploadStatus.Completed)
            {
                var file = uploadRequest.ResponseBody;
                return Ok($"上传成功,文件ID:{file.Id},文件名:{file.Name}");
            }
            else
            {
                return StatusCode(500, $"上传失败:{uploadResult.Exception?.Message}");
            }
        }
    }
}

注意事项

  • 服务账号默认有独立的Drive存储空间,要写入个人/组织的Drive必须提前分配对应文件夹的权限
  • 生产环境建议将密钥内容存到环境变量或者加密配置中心,不要明文存放在项目目录
  • 目标文件夹ID可从Google Drive网页端的文件夹URL获取,folders/后面的字符串即为文件夹ID

内容的提问来源于stack exchange,提问作者Mohammed Abdelwahab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:09:04