Upload file to Google drive


Please Share

Google Drive API

Are you working on an application where you would like to upload a file to Google drive. There are some changes from google drive v2 to the new Google drive v3 and a lot of the samples out there for v2 wont work for the new Google drive API v3.

Setup

The first thing you will need to do is create a new project on Google developer console. For this project i will be using a console application so we will create a native client. Note this code will NOT work for a web browser application.

You will also need the NuGet package Install-Package Google.Apis.Drive.v3

Code

I am passing the Json file which I downloaded from the Google Developer console and passing it directly to the getDriveService method. MyUser is just a string used to denote the user that the credentials will be saved under. If your intersted in reading how this works you may want to read my Filedatastore tutorial after that we pass the scopes that we need.

We use a file stream to load the file and the upload method to preform the upload. This is a simple upload method and will work for files under 5mb.

var service = Oauth2Example.GetDriveService(@"C:\Users\lilaw\Documents\.credentials\NativeClient.json", "MyUser",
                new[] {Google.Apis.Drive.v3.DriveService.Scope.Drive});

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = "flag.jpg"
            };

            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(@"C:\temp\flag.jpg", System.IO.FileMode.Open))
            {
                request = service.Files.Create(fileMetadata, stream, "image/jpeg");
                request.Fields = "id";
                request.Upload();
            }

            var file = request.ResponseBody;

            Console.WriteLine(file.Id);

Conclusion

Simple upload gives us a method for uploading small files to google drive. I would like to thank ChrisUK for being desprate enough that I finally got around to creating this tutorial.

Please Share


Linda Lawton

About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.