C#Google Drive APIv3上传文件

时间:2016-10-14 17:39:28

标签: c# oauth google-drive-api

我正在创建一个链接到Google云端硬盘帐户的简单应用程序,然后可以将文件上传到任何目录并使用(直接)下载链接进行响应。 我已经获得了用户凭据和DriveService对象,但我似乎无法找到任何好的示例或文档。在APIv3上。

由于我对OAuth不太熟悉,我现在要求就如何使用byte[]内容上传文件提出一个清晰明确的解释。

我将应用程序链接到Google云端硬盘帐户的代码:(不确定这是否完美)

    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) { }
    }

谢谢!

4 个答案:

答案 0 :(得分:6)

启用Drive API,注册项目并从Developer Consol获取凭据后,您可以使用以下代码获取用户的同意并获得经过身份验证的云端硬盘服务

<script>
  $("#test").fancybox({
  onClosed: function () {
  alert('sucess');
  })
    });
 </script>

以下是用于上传到云端硬盘的工作代码。

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.

这里是确定MimeType的小函数:

    // _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");
   }
}

此外,您可以注册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. 

在上载中几乎就是这样..

Source

答案 1 :(得分:2)

如果您已经关注Google Drive API's .NET Quickstart指南,那么您可能还记得在首次发布时,来自Google云端硬盘的网页提示授权授权访问Google驱动器,其中包含#34;只读&#34;许可?

默认范围&#34; DriveService.Scope.DriveReadonly&#34;如果您打算上传文件,则无法使用快速入门指南。

这对我有用

  1. 删除&#34; Drive ProtoType&#34;来自Apps connected to your account

  2. 使用新的应用程序名称创建另一组凭据,例如&#34; Drive API .NET Quickstart2&#34;在API Manager

  3. 使用此范围请求访问&#34; DriveService.Scope.DriveFile&#34;     private static readonly string [] Scopes = {DriveService.Scope.DriveReadonly};     private static readonly string ApplicationName =&#34; Drive API .NET Quickstart2&#34 ;;}

  4. 您应该从谷歌驱动器请求新的授权

    登陆新页面

    Drive Prototype希望:查看和管理您使用此应用打开或创建的Google云端硬盘文件和文件夹

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

答案 2 :(得分:0)

我对我的应用程序winforms c#fw 4.0有同样的问题 我已经安装了由nuget安装的google drive api v3 还从googles api创建了json文件并插入到项目中 request.ResponseBody == null ???

任何人都有解决方案吗?

感谢提前

答案 3 :(得分:0)

我认为你正朝着正确的方向前进,有点不确定。

使用Google Drive API进行C#(.NET)应用程序的主要步骤是

  1. 在您的Google帐户中启用Google云端硬盘API

  2. 使用&#34; NuGet&#34;安装Google Drive SDK for .NET framework。包经理。为此,在Visual Studio中,转到工具 - &gt; NuGet包管理器 - &gt;包管理器控制台,然后输入以下命令

    Install-Package Google.Apis.Drive.v3
    
  3. 确保您使用&#34;应用程序中的所有包/库使用&#34;使用&#34;顶部的陈述。例如,

    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. 您上面写的代码对我来说似乎是对的(我没有经过严格的测试)。但如果您在使用它上传文件时遇到问题,可以通过下面提到的链接尝试不同的方法。

  5. 以上步骤主要来自Google Drive API's .NET Quickstart页。

    此外,您可以并且应该参考Google's documentation for the Google Drive SDK for .NET framework

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