Google API使用验证服务帐户上传文件 [英] Google API to upload files using the Authentication Service Account

查看:158
本文介绍了Google API使用验证服务帐户上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过API Google Drive发送文件,但找不到有关如何使用认证服务帐户执行C#上传文件的任何文档。



<我下载了Daimto库,然而,当我们使用认证ClientId和ClientSecret时,他使用DriveService类上传。但使用帐户服务身份验证,他返回到PlusService类,并且没有办法以这种方式上传文件。



有人可以帮我吗?
最好的祝愿



使用身份验证服务帐户

  public PlusService GoogleAuthenticationServiceAccount()
{
String serviceAccountEmail =106842951064-6s4s95s9u62760louquqo9gu70ia3ev2@developer.gserviceaccount.com;

// var certificate = new X509Certificate2(@key.p12,notasecret,X509KeyStorageFlags.Exportable);
var certificate = new X509Certificate2(@key.p12,notasecret,X509KeyStorageFlags.Exportable);

ServiceAccountCredential凭证=新的ServiceAccountCredential(
新的ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new [] {PlusService.Scope.PlusMe}
} .FromCertificate(证书));

//创建服务。
var service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer =凭证,
ApplicationName =Plus API Sample,
});

退货服务;
}

使用身份验证ClientId和ClientSecret

 公共DriveService GoogleAuthentication(字符串userClientId,字符串userSecret)
{
//用于Google Drive API的范围
字符串[]作用域=新字符串[] {DriveService.Scope.Drive,DriveService.Scope.DriveFile};
//这里是我们要求用户给我们访问的地方,或者使用先前存储在%AppData%
中的刷新令牌UserCredential凭证= GoogleWebAuthorizationBroker.AuthorizeAsync(新的ClientSecrets {ClientId = userClientId,ClientSecret = userSecret},范围,Environment.UserName,CancellationToken.None,新的FileDataStore(Daimto.GoogleDrive.Auth.Store))。

DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer =凭证,
ApplicationName =Drive API Sample
}) ;

退货服务;
}

Daimto类方法可以将文件上传到谷歌驱动
DaimtoGoogleDriveHelper正如你所看到的,Daimto库有一个上传的方法,但是使用_service参数,这是DriveService类型,这是GoogleAuthentication方法返回的内容。但GoogleAuthenticationServiceAccount方法返回一个PlusService类型,并且与DriveService类型不兼容。

解决方案

我不确定我的哪一个教程你在追随。但你的第一部分代码是使用PlusService,你应该使用DriveService。您对Google驱动器API所做的任何请求都必须通过DriveService



使用服务帐号验证Google驱动器:

  ///< summary> 
///使用服务帐户向Google进行身份验证
///文档:https://developers.google.com/accounts/docs/OAuth2#serviceaccount
///< /总结>
///< param name =serviceAccountEmail>从Google Developer Console https://console.developers.google.com< / param>
///< param name =keyFilePath>从Google Developer控制台下载的服务帐户密钥文件的位置https://console.developers.google.com< / param>
///<返回>< /返回>
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail,string keyFilePath)
{

//检查文件是否存在
if(!File.Exists(keyFilePath))
{
Console.WriteLine(发生错误 - 密钥文件不存在);
返回null;
}

// Google Drive范围文档:https://developers.google.com/drive/web/scopes
string [] scopes = new string [] {DriveService .Scope.Drive,//查看和管理您的文件和文档
DriveService.Scope.DriveAppdata,//查看和管理自己的配置数据
DriveService.Scope.DriveAppsReadonly,//查看您的驱动器应用程序
DriveService.Scope.DriveFile,//查看和管理由此应用程序创建的文件
DriveService.Scope.DriveMetadataReadonly,//查看文件的元数据
DriveService.Scope.DriveReadonly,//查看文件和您的驱动器上的文档
DriveService.Scope.DriveScripts}; //修改你的应用脚本

var certificate = new X509Certificate2(keyFilePath,notasecret,X509KeyStorageFlags.Exportable);
尝试
{
ServiceAccountCredential凭证=新ServiceAccountCredential(
新ServiceAccountCredential.Initializer(serviceAccountEmail)
{
范围=范围
} .FromCertificate (证书));

//创建服务。
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer =凭证,
ApplicationName =Daimto Drive API Sample,
});
退货服务;
}
catch(Exception ex)
{
Console.WriteLine(ex.InnerException);
返回null;




上传file:

  private static string GetMimeType(string fileName)
{
string mimeType =application / unknown ;
字符串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();
返回mimeType;
}

///< summary>
///上传文件
///文档:https://developers.google.com/drive/v2/reference/files/insert
///< / summary>
///< param name =_ service> a有效的认证DriveService< / param>
///< param name =_ uploadFile>要上传文件的路径< / param>
///< param name =_ parent>收集包含此文件的父文件夹。
///设置此字段将把文件放入所有提供的文件夹中。根文件夹。< / param>
///< returns>如果上传成功返回上传文件的文件资源
///如果上传失败返回null< / returns>
public static File uploadFile(DriveService _service,string _uploadFile,string _parent){

if(System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description =由Diamto Drive Sample上传的文件;
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);
尝试
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body,stream,GetMimeType(_uploadFile));
request.Upload();
返回request.ResponseBody;

catch(Exception e)
{
Console.WriteLine(发生错误:+ e.Message);
返回null;
}
}
else {
Console.WriteLine(File does not exist:+ _uploadFile);
返回null;
}

}

如果上传代码相同您使用的是Oauth2或服务帐户,没有任何区别。



从Google Drive .net样本上撕下的代码 Github
教程: Google Drive API with C#.net - 下载


I'm trying to send files by API Google Drive, though, I can not find any documentation on how to perform C # Uploading files using the Authentication Service Account.

I downloaded the Daimto library, however, he uploads using the DriveService class, when we use the authentication ClientId and ClientSecret. But using authentication for account service he returns to PlusService class, and found no way to upload files this way.

Can someone help me? Best regards

Using Authentication Service Account

    public PlusService GoogleAuthenticationServiceAccount()
    {
        String serviceAccountEmail = "106842951064-6s4s95s9u62760louquqo9gu70ia3ev2@developer.gserviceaccount.com";

        //var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
        var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
               Scopes = new[] { PlusService.Scope.PlusMe }
           }.FromCertificate(certificate));

        // Create the service.
        var service = new PlusService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Plus API Sample",
        });

        return service;
    }

Using Authentication ClientId and ClientSecret

    public DriveService GoogleAuthentication(string userClientId, string userSecret)
    {
        //Scopes for use with the Google Drive API
        string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = userClientId, ClientSecret = userSecret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GoogleDrive.Auth.Store")).Result;

        DriveService service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Drive API Sample"
        });

        return service;
    }

Daimto class method that makes the file upload to google drive DaimtoGoogleDriveHelper.uploadFile(_service, fileName, item.NomeArquivo, directoryId);

As you can see, the Daimto library, has a method to upload, however, uses the _service parameter, which is the DriveService type, which is what is returned by GoogleAuthentication method. But the GoogleAuthenticationServiceAccount method returns a PlusService type and is incompatible with the DriveService type.

解决方案

I am not sure which one of my tutorials you are following. But your first hunk of code is using a PlusService you should be using a DriveService. Any requests you make to the Google drive API must go though a DriveService

Authenticating to Google drive with a service account:

/// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns></returns>
        public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
        {

            // check the file exists
            if (!File.Exists(keyFilePath))
            {
                Console.WriteLine("An Error occurred - Key file does not exist");
                return null;
            }

            //Google Drive scopes Documentation:   https://developers.google.com/drive/web/scopes
            string[] scopes = new string[] { DriveService.Scope.Drive,  // view and manage your files and documents
                                             DriveService.Scope.DriveAppdata,  // view and manage its own configuration data
                                             DriveService.Scope.DriveAppsReadonly,   // view your drive apps
                                             DriveService.Scope.DriveFile,   // view and manage files created by this app
                                             DriveService.Scope.DriveMetadataReadonly,   // view metadata for files
                                             DriveService.Scope.DriveReadonly,   // view files and documents on your drive
                                             DriveService.Scope.DriveScripts };  // modify your app scripts     

            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                   {
                       Scopes = scopes
                   }.FromCertificate(certificate));

                // Create the service.
                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Daimto Drive API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return null;

            }
        }
    }

Upload a file:

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;
        }

        /// <summary>
        /// Uploads a file
        /// Documentation: https://developers.google.com/drive/v2/reference/files/insert
        /// </summary>
        /// <param name="_service">a Valid authenticated DriveService</param>
        /// <param name="_uploadFile">path to the file to upload</param>
        /// <param name="_parent">Collection of parent folders which contain this file. 
        ///                       Setting this field will put the file in all of the provided folders. root folder.</param>
        /// <returns>If upload succeeded returns the File resource of the uploaded file 
        ///          If the upload fails returns null</returns>
        public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {

            if (System.IO.File.Exists(_uploadFile))
            {
                File body = new File();
                body.Title = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File uploaded by Diamto Drive Sample";
                body.MimeType = GetMimeType(_uploadFile);
                body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };

                // File's content.
                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)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return null;
                }
            }
            else {
                Console.WriteLine("File does not exist: " + _uploadFile);
                return null;
            }           

        }

The upload code is the same if you are using Oauth2 or a service account there is no difference.

Code ripped from Google Drive .net sample on Github Tutorial: Google Drive API with C# .net – Download

这篇关于Google API使用验证服务帐户上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆