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

.NET Maui跨平台项目:如何上传文件到Google Drive并获取ID/下载链接

.NET Maui 上传文件至Google Drive 实现方案

前置准备

  • 登录Google Cloud Console,创建新项目并启用Google Drive API
  • 创建OAuth 2.0客户端ID,选择「Desktop app」类型(跨平台兼容),下载JSON配置文件后放入项目,设置文件属性为「复制到输出目录:如果较新则复制」
  • 安装必要NuGet包:Google.Apis.Drive.v3、Google.Apis.Auth、Microsoft.AspNetCore.StaticFiles(用于获取MIME类型)

授权逻辑实现

首先实现Google Drive的授权流程,获取用户凭证:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Threading;

public static async Task<UserCredential> GetDriveCredentialAsync()
{
    // 仅请求文件操作权限,遵循最小权限原则
    string[] scopes = { DriveService.Scope.DriveFile };
    // 从JSON配置文件加载客户端信息
    using var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read);
    var secrets = await GoogleClientSecrets.FromStreamAsync(stream);

    return await GoogleWebAuthorizationBroker.AuthorizeAsync(
        secrets.Secrets,
        scopes,
        "user",
        CancellationToken.None,
        new FileDataStore("MauiDriveAuthStore", true));
}

注意:移动端(Android/iOS)使用GoogleWebAuthorizationBroker可能无法直接弹出授权页,需改用WebView加载授权URL,获取回调的授权码后兑换凭证,或使用Google.Apis.Auth.Maui专用包简化流程。

文件上传实现

编写通用上传方法,支持PDF、PNG等任意文件,返回文件ID和下载链接:

using Microsoft.AspNetCore.StaticFiles;

public static async Task<(string FileId, string DownloadLink)> UploadFileToDriveAsync(UserCredential credential, string filePath, string targetFolderId = null)
{
    var driveService = new DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "你的Maui项目名称"
    });

    // 获取文件MIME类型
    var contentTypeProvider = new FileExtensionContentTypeProvider();
    if (!contentTypeProvider.TryGetContentType(filePath, out var contentType))
    {
        contentType = "application/octet-stream"; // 默认兜底类型
    }

    // 构建文件元数据
    var fileMetadata = new Google.Apis.Drive.v3.Data.File()
    {
        Name = Path.GetFileName(filePath),
        Parents = targetFolderId != null ? new List<string> { targetFolderId } : null // 可选:指定上传到目标文件夹
    };

    // 创建上传请求
    using var fileStream = new FileStream(filePath, FileMode.Open);
    var uploadRequest = driveService.Files.Create(fileMetadata, fileStream, contentType);
    uploadRequest.Fields = "id,webContentLink"; // 指定返回文件ID和直接下载链接

    // 执行上传
    await uploadRequest.UploadAsync();
    var uploadedFile = uploadRequest.ResponseBody;

    return (uploadedFile.Id, uploadedFile.WebContentLink);
}

在Maui界面中调用

结合FilePicker选择文件,触发上传流程:

private async void UploadBtn_Clicked(object sender, EventArgs e)
{
    // 选择PDF/PNG文件
    var pickResult = await FilePicker.PickAsync(new PickOptions
    {
        FileTypes = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
        {
            { DevicePlatform.Android, new[] { "application/pdf", "image/png" } },
            { DevicePlatform.iOS, new[] { "public.pdf", "public.png" } },
            { DevicePlatform.WinUI, new[] { ".pdf", ".png" } }
        })
    });

    if (pickResult == null) return;

    try
    {
        // 获取授权凭证
        var credential = await GetDriveCredentialAsync();
        // 执行上传
        var (fileId, downloadLink) = await UploadFileToDriveAsync(credential, pickResult.FullPath);
        
        await DisplayAlert("上传成功", $"文件ID:{fileId}\n下载链接:{downloadLink}", "确认");
    }
    catch (Exception ex)
    {
        await DisplayAlert("上传失败", ex.Message, "确认");
    }
}

关键注意事项

  • 权限配置:优先使用DriveFile scope而非全权限Drive,降低安全风险
  • 移动端适配:Android需在AndroidManifest.xml配置OAuth回调的URL Scheme;iOS需在Info.plist中添加CFBundleURLTypes
  • 大文件处理:上传大文件时启用分块上传,设置uploadRequest.ChunkSize = ResumableUpload.MinimumChunkSize;并监听上传进度
  • 永久下载链接:webContentLink是临时链接,若需永久访问,可设置文件权限为「Anyone with link can view」,然后使用https://drive.google.com/uc?id={fileId}&export=download作为固定下载链接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:01:21