2
votes

I am trying to upload image file to google drive using service account.
In service account I followed below steps :
1) Created new project on developer console
2) In APIs & auth turned ON the drive api.
3) Generated new client id under service account
4) Also generated P12 key.
After that I have written below code for uploading image on google drive using 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;

Upload is failing here, when I tried to debug the code I found "request.ResponseBody" is null.

Can anybody please help me on this ?

1
where your code says "File file = request.ResponseBody;", what does file contain?pinoyyid

1 Answers

0
votes

Your code isn't that different from what I normally use. The only thing I can see off hand that you may be missing is the parent. I cant see any mention in the documentation that parent is required but it might be.

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

Code ripped from Google-dotnet-Samples project on GitHub