Thursday, June 28, 2018

[Google Driver API]Uploading and viewing file by Google Driver API

There is a solution for uploading and viewing file by Gooole Driver API.

Step 1 Enable Google API nad get the client_secret

 Here is the official reference link: https://developers.google.com/drive/api/v3/quickstart/js

a. Create your project
b. On the Add credentials to your project page, click the Cancel button

c. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button

d. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
e. Dowload the client_secret.json


f. Put the client_secret.json to your project.


Step 2 Install Google.Apis.Driver.v3 as Nuget


Step 3 Write code in your Controller

static string[] Scopes = { DriveService.Scope.Drive };
static string ApplicationName = "Drive API .NET Quickstart";

private DriveService GetService()
{
     UserCredential credential;

     using (var stream = new FileStream(Server.MapPath("~/Content/client_secret.json"), FileMode.Open, FileAccess.Read))
     {
          string credPath = System.Environment.GetFolderPath(
          System.Environment.SpecialFolder.Personal);

          credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

          credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
     }

     // Create Drive API service.
     var service = new DriveService(new BaseClientService.Initializer()
     {
          HttpClientInitializer = credential,
          ApplicationName = ApplicationName,
     });

     return service;
}
public ActionResult Upload()
{
     DriveService service = GetService();

     string fileName = "template.odt";

     var fileMetadata = new Google.Apis.Drive.v3.Data.File()
     {
          Name = fileName,
          MimeType = MimeMapping.GetMimeMapping(fileName)
     };

      FilesResource.CreateMediaUpload request;
      using (var stream = new System.IO.FileStream(Server.MapPath("~/Content/template.odt"), System.IO.FileMode.Open))//~/Content/template.odt is your file location
      {
           request = service.Files.Create(
                    fileMetadata,
                    stream,
                    MimeMapping.GetMimeMapping(fileName));
                    request.Fields = "id";
                    request.Upload();
      }
      var ftwile = request.ResponseBody;

      return Redirect(string.Format("https://drive.google.com/file/d/{0}/view", ftwile.Id));
}
Just put
<a href='@Url.Action("Upload")'>Upload</a>
on your View file.
Click the link it will upload file and open the file on google driver.