View Uploaded Files in Google Drive from ASP.NET Core App

To implement a solution that allows users to view different file formats (like doc, pdf, excel, ppt) in Google Drive from a local path folder or an S3 bucket in an ASP.NET Core web application, you can follow these steps.

  1. Set Up Google Drive API
    • Create a Google Cloud project and enable the Google Drive API.
    • Create OAuth 2.0 credentials (Client ID and Client Secret).
    • Configure the consent screen and add the necessary scopes for accessing and managing Google Drive files.
  2. Install Google API Client Libraries
    • Install the Google API client libraries for .NET via the NuGet package manager.
      dotnet add package Google.Apis.Drive.v3
      dotnet add package Google.Apis.Auth
      
  3. Configure Google API in ASP.NET Core Application
    • Store your OAuth 2.0 credentials in your configuration file (appsettings.json).
    • Create a service to handle Google Drive operations.
  4. Upload Files to Google Drive
    • Implement functionality to upload files from the local path folder or S3 bucket to Google Drive.
  5. Generate Google Drive Viewer Links
    • Once the files are uploaded to Google Drive, generate viewer links that can be used to view the files directly in the browser.
  6. Integrate with ASP.NET Core MVC or Razor Pages
    • Create views and controllers to handle file upload and display the Google Drive viewer links.

Here's a detailed implementation

Step 1. Set Up Google Drive API.

  1. Go to the Google Cloud Console.
  2. Create a new project.
  3. Navigate to "API & Services" > "Library".
  4. Enable the Google Drive API.
  5. Navigate to "API & Services" > "Credentials".
  6. Create OAuth 2.0 Client IDs and download the JSON file.

Step 2. Install Google API Client Libraries.

Install the necessary NuGet packages.

dotnet add package Google.Apis.Drive.v3
dotnet add package Google.Apis.Auth

Step 3. Configure Google API in ASP.NET Core.

appsettings.json

{
  "GoogleDrive": {
    "ClientId": "YOUR_CLIENT_ID",
    "ClientSecret": "YOUR_CLIENT_SECRET",
    "RedirectUri": "YOUR_REDIRECT_URI"
  }
}

Step 4. Implement Google Drive Service.

Create a service to handle Google Drive operations.

GoogleDriveService.cs

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Upload;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class GoogleDriveService
{
    private readonly DriveService _driveService;

    public GoogleDriveService(IConfiguration configuration)
    {
        var clientId = configuration["GoogleDrive:ClientId"];
        var clientSecret = configuration["GoogleDrive:ClientSecret"];
        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            },
            new[] { DriveService.Scope.DriveFile },
            "user",
            CancellationToken.None).Result;

        _driveService = new DriveService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = "YourAppName"
        });
    }

    public async Task<string> UploadFileAsync(string path)
    {
        var fileMetadata = new Google.Apis.Drive.v3.Data.File
        {
            Name = Path.GetFileName(path)
        };

        using (var stream = new FileStream(path, FileMode.Open))
        {
            var request = _driveService.Files.Create(fileMetadata, stream, GetMimeType(path));
            request.Fields = "id";
            var result = await request.UploadAsync();

            if (result.Status == UploadStatus.Failed)
            {
                throw new Exception($"Error uploading file: {result.Exception.Message}");
            }

            return request.ResponseBody.Id;
        }
    }

    public string GetFileLink(string fileId)
    {
        return $"https://drive.google.com/file/d/{fileId}/view";
    }

    private string GetMimeType(string fileName)
    {
        var mimeType = "application/octet-stream";
        var ext = Path.GetExtension(fileName).ToLowerInvariant();
        switch (ext)
        {
            case ".pdf":
                mimeType = "application/pdf";
                break;
            case ".doc":
            case ".docx":
                mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                break;
            case ".xls":
            case ".xlsx":
                mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                break;
            case ".ppt":
            case ".pptx":
                mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                break;
        }
        return mimeType;
    }
}

Step 5. Create a Controller and View.

FilesController.cs

using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;

public class FilesController : Controller
{
    private readonly GoogleDriveService _googleDriveService;

    public FilesController(GoogleDriveService googleDriveService)
    {
        _googleDriveService = googleDriveService;
    }

    [HttpPost]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file != null && file.Length > 0)
        {
            var path = Path.GetTempFileName();
            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var fileId = await _googleDriveService.UploadFileAsync(path);
            var link = _googleDriveService.GetFileLink(fileId);

            ViewBag.FileLink = link;
        }

        return View();
    }

    public IActionResult Index()
    {
        return View();
    }
}

Index. cshtml

@{
    ViewData["Title"] = "Upload File";
}

<h1>Upload File</h1>

<form asp-action="Upload" asp-controller="Files" enctype="multipart/form-data" method="post">
    <input type="file" name="file" />
    <button type="submit">Upload</button>
</form>

@if (ViewBag.FileLink != null)
{
    <h2>File Link</h2>
    <a href="@ViewBag.FileLink" target="_blank">View File</a>
}

Step 6. Integrate with S3 (if needed).

If you want to upload files from an S3 bucket, you can modify the UploadFileAsync method to download the file from S3 first and then upload it to Google Drive.

public async Task<string> UploadFileFromS3Async(string s3BucketName, string s3Key)
{
    using (var client = new AmazonS3Client())
    {
        var request = new GetObjectRequest
        {
            BucketName = s3BucketName,
            Key = s3Key
        };

        using (var response = await client.GetObjectAsync(request))
        using (var stream = response.ResponseStream)
        {
            var path = Path.GetTempFileName();
            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                await stream.CopyToAsync(fileStream);
            }

            return await UploadFileAsync(path);
        }
    }
}

By following these steps, you can implement a solution in your ASP.NET Core web application to allow users to upload files and view them directly in Google Drive without the need to download them.


Similar Articles