Upload to Drive [closed]

1

Personal I have the following code, which opens the consent form of google, where the authorization of the user is made and an authentication token is generated:

public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
{
    var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
    AuthorizeAsync(cancellationToken);

    if (result.Credential != null)
    {
        ViewBag.Message = result.Credential.UserId;
        DriveService service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = result.Credential,
            ApplicationName = "DriveApi",
        });
        return View();
    }
    else
    {
        return new RedirectResult(result.RedirectUri);
    }
}

I'm actually stuck in this part:

DriveService service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = result.Credential,
                ApplicationName = "DriveApi",
            });

I just need to call this part inside a static method, because after I do the authentication only the DriveService will be necessary, but when doing this part in a static method the result.Credential does not exist, there is only the result. And I need Credential to make everything work properly.

But now I need to upload the file, but I do not find anything on the internet about how to do it that is clear, someone has already worked with it and could help me?

    
asked by anonymous 04.04.2017 / 19:12

1 answer

4

Let's break it down.

First, the OAuth sample in Asp.NET MVC you can see here , but I will transcribe the form of use here.

Install the Google Auth MVC Extensions API , with the following command in Package Manager Console:

  

Install-Package Google.Apis.Auth.Mvc

Once this is done, we will first have to create AppFlowMetadata .

  

FlowMetadata is an abstract class that contains its own logic to retrieve the user identifier and what IAuthorizationCodeFlow you are using.

The code would be this:

using System;
using System.Web.Mvc;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;

namespace Google.Apis.Sample.MVC4
{
    public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }
}

Now, let's implement our AuthCallbackController , which will be Google's return URL.

using Google.Apis.Sample.MVC4;

namespace Google.Apis.Sample.MVC4.Controllers
{
    public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
    {
        protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData
        {
            get { return new AppFlowMetadata(); }
        }
    }
}
  

NOTE: Do not forget to add this return URL in your app's Console to Google.

Once this is done, we'll go to HomeController , where we'll upload the file, you can see the Google example here.

public class HomeController : Controller
{
    public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
    {
        var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
            AuthorizeAsync(cancellationToken);

        if (result.Credential != null)
        {
            var service = new DriveService(new BaseClientService.Initializer
            {
                HttpClientInitializer = result.Credential,
                ApplicationName = "ASP.NET MVC Sample"
            });

            // YOUR CODE SHOULD BE HERE..
            // SAMPLE CODE:
            var list = await service.Files.List().ExecuteAsync();
            ViewBag.Message = "FILE COUNT IS: " + list.Files.Count();

            var fileMetadata = new File()
            {
                Name = "photo.jpg"
            };
            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(@"C:\Users\CAMINHO_DA_IMAGEM_AQUI",
                                    System.IO.FileMode.Open))
            {
                request = service.Files.Create(
                    fileMetadata, stream, "image/png");
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;


            return View();
        }
        else
        {

            var pause = true;
            return new RedirectResult(result.RedirectUri);
        }
    }
}

Note that I changed only to return a ActionResult , but the upload part remains the same.

Note that in this example, a file named photo.jpg will be created in the user's Google Drive.

    
04.04.2017 / 20:48