c# - 无法使用服务帐户在谷歌驱动器上上传图片

标签 c# .net google-drive-api google-api-dotnet-client

我正在尝试使用服务帐户将图像文件上传到谷歌驱动器。
在服务帐户中,我按照以下步骤操作:
1) 在开发者控制台创建新项目
2) 在 APIs & auth 中打开驱动器 api。
3) service account下生成新的client id
4) 同时生成P12 key 。
之后,我编写了以下代码,用于使用 SERVICE ACCOUNT 在 google drive 上上传图片:

X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
 {
    Scopes = new[] { DriveService.Scope.DriveReadonly }
 }.FromCertificate(certificate));

// Create the service.
     var service = new DriveService(new BaseClientService.Initializer()
    {
                HttpClientInitializer = credential,
                ApplicationName = "Drive API Sample",
    });
File body = new File();
body.Title = "My Sample Image";
body.Description = "Image";
body.MimeType = "image/jpeg";
byte[] byteArray = System.IO.File.ReadAllBytes("image.jpeg");
System.IO.File.Delete("image.jpeg");

System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/jpeg");
request.Upload();
File file = request.ResponseBody;

此处上传失败,当我尝试调试代码时发现“request.ResponseBody”为空。

谁能帮我解决这个问题?

最佳答案

您的代码与我通常使用的代码没有什么不同。我唯一能看到你可能缺少的是 parent 。我在文档中看不到任何提到 parent 是必需的,但它可能是。

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

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

Google-dotnet-Samples 中提取的代码GitHub上的项目

关于c# - 无法使用服务帐户在谷歌驱动器上上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28718692/

相关文章:

python - 如何使用 Python 将 .docx 文件上传到我的 Google 云端硬盘?

c# - 如何使用框架或内置功能将代码作为步骤执行?

c# - 具有动态端点映射的最小 Api 通用 CRUD

c# - 如何从根 url 重定向到/swagger/ui/index?

c# - 为什么我不能将派生泛型类型转换为基本非泛型类型(通过约束)?

c# - 如何在 C# 中使用 TransactionScope?

c# - 什么是NullReferenceException,如何解决?

c# - 如何从电子表格中删除过滤后的数据?

python - unauthorized_client : Client is unauthorized to retrieve access tokens using this method

java - 捕获 GoogleJsonResponseException 但 e.getDetails() 返回 null