【问题标题】:Not able upload an image on google drive using service account无法使用服务帐户在谷歌驱动器上上传图片
【发布时间】:2015-02-25 12:09:00
【问题描述】:

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

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”为空。

有人可以帮我吗?

【问题讨论】:

  • 您的代码在哪里显示“文件文件 = request.ResponseBody;”,文件包含什么?

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


【解决方案1】:

您的代码与我通常使用的代码没有什么不同。我唯一能看到的你可能会想念的是父母。我在文档中看不到任何提及需要 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;
        }

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

【讨论】:

  • 我添加了父级并将其设置为“根”,但它对我不起作用..我遇到异常:异常 = {“值不能为空。\r\n参数名称:baseUri "}
  • 它是否返回任何错误?您是否尝试过执行 listfiles 来查看文件是否正在上传?
  • 我只是更新了示例项目以使用服务帐户或 Oauth2。展示如何上传、更新和下载文件。
  • @DaImTo 哎呀我的错。我的意思是问OP
猜你喜欢
  • 2014-06-22
  • 2022-07-25
  • 2014-02-21
  • 1970-01-01
  • 2013-04-07
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多