c# Google Drive APIv3上传文件

本文关键字:文件 APIv3 Google Drive | 更新日期: 2023-09-27 18:13:03

我正在制作一个简单的应用程序,链接到谷歌驱动器帐户,然后可以将文件上传到任何目录并响应(直接)下载链接。我已经得到了我的用户凭证和DriveService对象,但我似乎找不到任何好的例子或文档。

由于我对OAuth不太熟悉,所以我要求一个关于如何上传byte[]内容的文件的清晰解释。

我的代码链接应用程序到一个谷歌驱动器帐户:(不确定如果这工作完美)

    UserCredential credential;

        string dir = Directory.GetCurrentDirectory();
        string path = Path.Combine(dir, "credentials.json");
        File.WriteAllBytes(path, Properties.Resources.GDJSON);
        using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
            string credPath = Path.Combine(dir, "privatecredentials.json");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }
        // Create Drive API service.
        _service = new DriveService(new BaseClientService.Initializer() {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        File.Delete(path);

我的代码上传到目前为止:(不工作明显)

        public void Upload(string name, byte[] content) {
        Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
        body.Name = name;
        body.Description = "My description";
        body.MimeType = GetMimeType(name);
        body.Parents = new List() { new ParentReference() { Id = _parent } };

        System.IO.MemoryStream stream = new System.IO.MemoryStream(content);
        try {
            FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
            request.Upload();
            return request.ResponseBody;
        } catch(Exception) { }
    }

谢谢!

c# Google Drive APIv3上传文件

一旦您启用了驱动器API,注册了您的项目并从开发人员控制台获得了凭据,您可以使用以下代码来接收用户的同意并获得经过身份验证的驱动器服务

string[] scopes = new string[] { DriveService.Scope.Drive,
                             DriveService.Scope.DriveFile};
var clientId = "xxxxxx";      // From https://console.developers.google.com
var clientSecret = "xxxxxxx";          // From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
                                                                              ClientSecret = clientSecret},
                                                        scopes,
                                                        Environment.UserName,
                                                        CancellationToken.None,
                                                        new FileDataStore("MyAppsToken")).Result; 
//Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent. 
DriveService service = new DriveService(new BaseClientService.Initializer()
{
   HttpClientInitializer = credential,
   ApplicationName = "MyAppName",
});
service.HttpClient.Timeout = TimeSpan.FromMinutes(100); 
//Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.

下面是上传到Drive的工作代码。

    // _service: Valid, authenticated Drive service
    // _uploadFile: Full path to the file to upload
    // _parent: ID of the parent directory to which the file should be uploaded
public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
{
   if (System.IO.File.Exists(_uploadFile))
   {
       File body = new File();
       body.Title = System.IO.Path.GetFileName(_uploadFile);
       body.Description = _descrp;
       body.MimeType = GetMimeType(_uploadFile);
       body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
       byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
       System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
       try
       {
           FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
           request.Upload();
           return request.ResponseBody;
       }
       catch(Exception e)
       {
           MessageBox.Show(e.Message,"Error Occured");
       }
   }
   else
   {
       MessageBox.Show("The file does not exist.","404");
   }
}

下面是确定mime类型的小函数:

private static string GetMimeType(string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
        mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}

另外,您可以注册ProgressChanged事件并获取上传状态。

 request.ProgressChanged += UploadProgessEvent;
 request.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize; // Minimum ChunkSize allowed by Google is 256*1024 bytes. ie 256KB. 

 private void UploadProgessEvent(Google.Apis.Upload.IUploadProgress obj)
 {
     label1.Text = ((obj.ByteSent*100)/TotalSize).ToString() + "%";
    // do updation stuff
 }

上传就到这里了

如果你遵循了Google Drive API的。net快速入门指南,那么你可能记得在第一次启动时,Google Drive的一个网页提示授权授予以"只读"权限访问Google Drive ?

默认作用域"DriveService.Scope"。如果你打算上传文件,不能使用快速入门指南中的DriveReadonly。

This works for me

  1. 从连接到您帐户的应用程序中删除"Drive ProtoType"

  2. 在API管理器

  3. 中使用新的应用程序名称创建另一组凭据,例如"Drive API .NET Quickstart2"
  4. 请求使用"DriveService.Scope.DriveFile"范围访问private static readonly string[] Scopes = {DriveService.Scope.DriveReadonly};私有静态只读字符串ApplicationName = "Drive API .NET Quickstart2";}

  5. 你应该登陆一个新的页面从google drive请求新的授权

    驱动器原型想:查看和管理谷歌驱动器文件和文件夹,你已经打开或创建与此应用程序

允许访问后,您的应用程序应该能够上传

我在我的应用程序winforms c# fw 4.0上有同样的问题我已经通过nuget安装了Google drive API v3并从谷歌API创建json文件,并插入到项目中请求。ResponseBody == null??

有人有解决办法吗?

thanks by advance

我认为你的方向是对的,只是有点不确定。

为c# (.NET)应用程序使用Google Drive API的主要步骤是

  1. 启用Google Drive API在您的Google帐户

  2. 使用"NuGet"包管理器为。net框架安装Google Drive SDK。为此,在Visual Studio中,转到Tools -> NuGet Package Manager -> Package Manager Console,然后输入以下命令

    Install-Package Google.Apis.Drive.v3
    
  3. 确保你在你的应用中使用了顶部的"using"语句来"使用"所有的包/库。例如,

    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Drive.v3;
    using Google.Apis.Drive.v3.Data;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;
    
  4. 你上面写的代码对我来说似乎是正确的(我没有认真测试过)。但是如果你在上传文件时遇到麻烦,你可以通过下面提到的链接尝试不同的方法。

以上步骤大部分取自Google Drive API的。net快速入门页。

此外,您可以并且应该参考Google的。net框架的Google Drive SDK文档。

希望以上内容对您有所帮助。