Upload to Drive

Asked

Viewed 743 times

1

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

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 on this part:

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

Only it happens that I need to call this part inside a Static method, because after I authenticate only Driveservice will be necessary, only when doing this part in a Static method the result. Credential does not exist, there is only the result. And need Credential for everything to work correctly.

Only now I need to upload the file, only I didn’t find anything on the internet about how to do it that is clear, someone has worked with it and could help me?

  • You want to upload an existing file, you want the user to upload the file, which is exactly what you want?

  • So it’s an existing file on the machine, which will be uploaded to the user’s drive.

  • Want to upload to a user account or to a pre-defined Google Drive account?

  • Upload to user account

1 answer

4


Let’s go in pieces.

First, The example of Oauth in Asp.NET MVC you can see here, but I will transcribe the form of use here.

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

Install-Package Google.Apis.Auth.Mvc

Once that’s done, we’ll first have to create AppFlowMetadata.

Flowmetadata It 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: Don’t forget to add this return URL to your app’s Google Console.

Once that’s done, we’ll go to HomeController, where we upload the file, which you can see the example of Google 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 one ActionResult, but the upload part remains the same.

Note that in this example, a file called photo.jpg in the user’s Google Drive.

  • Friend I am only having a problem, that for each session is being generated a different token, only for that it is necessary to do this authentication process again, however it is not necessary to accept anything if I have already accepted once, it is necessary to open the screen to run the "Googleauthorizationcodeflow" to generate another token, and from there upload, know what could be happening?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.