无法使用服务帐户在Google云端硬盘上传图像

时间:2015-02-25 12:09:01

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

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

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

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您的代码与我通常使用的代码不同。我唯一可以看到你可能遗失的是父母。我不能在文档中看到父母是必需的,但可能是。

 /// <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项目中删除