Learn ASP.NET Core 3.1 : MVC, Razor Pages, Web API, Entity Framework Core, and Blazor.
Microsoft's official documentation can be found here. Looking for professional online training courses? Next weekend batches are starting in March 2020. More details here.

Download and Upload Google Drive Files in ASP.NET Core

In the previous article we displayed a list of files from Google Drive. By now you know how to configure a Google API project and establish a connection with your Google drive. In this part you will build on top of what you learned in the previous part. Firstly you will provide Download functionality to the list of files displayed in the browser. The downloaded file(s) is saved in the wwwroot folder and can be used by your application for further processing. Secondly, you will also learn to upload files from your ASP.NET Core web application to the Google drive.

Let's get going.

First, let's implement downloading functionality. Recollect that in the previous part you displayed File Id and File Name in a table. Modify that table to have a Download link as shown below: 

To display this Download link you need to modify the Index.cshtml markup like  this:

@model List<GoogleDriveFileEntry>

<table border="1" width="10%" cellpadding="6">
    <tr>
        <th>File ID</th>
        <th>File Name</th>
    </tr>
    @foreach(var item in Model)
    {
        <tr>
            <td>@item.FileName</td>
            <td><a href="/Home/
Download?fileid=@item.FileId&
fileName=@item.FileName">Download</a></td>
        </tr>
    }
</table>

As you can see, a hyperlink is added to the table that contains FileId and FileName in the query string. You need both because you would like to save the file in wwwroot with the same name as on the Google drive. The link calls the Download() action of the HomeController and is shown below.

public IActionResult Download(string fileId,string fileName)
{
    var clientId = config.GetValue<string>
("GoogleDrive:ClientId");
    var clientSecret = config.GetValue<string>
("GoogleDrive:ClientSecret");
    var userName = config.GetValue<string>
("GoogleDrive:UserName");

    var clientSecrets = new ClientSecrets()
    {
        ClientId = clientId,
        ClientSecret = clientSecret
    };

    string[] scopes = new string[] {
        DriveService.Scope.Drive,
        DriveService.Scope.DriveFile
    };

    var userCredential = GoogleWebAuthorizationBroker.
AuthorizeAsync
        (clientSecrets,
        scopes,
        userName,
        CancellationToken.None).Result;

    var driveService = new DriveService(new 
BaseClientService.Initializer()
    {
        HttpClientInitializer = userCredential,
        ApplicationName = "Google Drive API Demo",
    });

    FilesResource.GetRequest getRequest = 
driveService.Files.Get(fileId);

    System.IO.FileStream fileStream = 
System.IO.File.Create($"{env.WebRootPath}\\{fileName}");

    getRequest.Download(fileStream);

    fileStream.Flush();
    fileStream.Close();

    return View();
}

The initial code from Download() action is the same as in the Index() action. Notice the code marked in bold letters.

The Get() method of Files accepts a FileId of a file to be retrieved from Google drive. And returns a GetRequest object. Then a FileStream is constructed that points to a new file under wwwroot folder. This is done using the Create() method.

Then Download() method of GetRequest is called by passing the FileStream object to it. The FileStream is flushed and closed to ensure that the file is properly saved in the wwwroot folder.

You can run the application and try clicking on any Download link. If all goes well that file will be downloaded and saved to the wwwroot folder with the same name.

Now that file download functionality has been implemented, let's upload a sample image file to the Google drive.

Add any image file to the wwwroot folder that you wish to upload on the Google drive. In a more realistic case you might have a file upload form or might pick the file from the server or database based on some application specific logic. Here, for the sake of simplicity we will use a test JPEG file.

Next, add a new action named Upload() in the HomeController and write the following code in it.

public IActionResult Upload(string fileName)
{
    var clientId = config.GetValue<string>
("GoogleDrive:ClientId");
    var clientSecret = config.GetValue<string>
("GoogleDrive:ClientSecret");
    var userName = config.GetValue<string>
("GoogleDrive:UserName");

    var clientSecrets = new ClientSecrets()
    {
        ClientId = clientId,
        ClientSecret = clientSecret
    };

    string[] scopes = new string[] {
        DriveService.Scope.Drive,
        DriveService.Scope.DriveFile
    };

    var userCredential = GoogleWebAuthorizationBroker.
AuthorizeAsync
        (clientSecrets,
        scopes,
        userName,
        CancellationToken.None).Result;

    var driveService = new DriveService(
new BaseClientService.Initializer()
    {
        HttpClientInitializer = userCredential,
        ApplicationName = "Google Drive API Demo",
    });

    File file = new File();
    file.Name = fileName;
    file.Description = "File uploaded to 
Google Drive from ASP.NET Core";
    file.MimeType = "image/jpeg";

    System.IO.FileStream fileStream = 
System.IO.File.OpenRead($"{env.WebRootPath}\\{fileName}");

    FilesResource.CreateMediaUpload uploadRequest = 
driveService.Files.Create(file, fileStream, "image/jpeg");
    uploadRequest.Upload();

    return View();
}

Notice the code marked in bold letters. The code first creates a File metadata object and sets metadata properties such as Name, Description, and MIME content type.

Then the code creates a FileStream that opens the sample file in read mode. This is done using OpenRead() method.

Next, the code creates an CreateMediaUpload object by calling Create() method on the File object. The Create() method accepts File metadata object, FileStream containing the contents of the file, and MIME content type of the file.

Finally, the Upload() method of CreateMediaUpload object is called to upload the file to the Google drive.

If you run this code you will see the sample file being uploaded to the Google drive as shown below:

If you see the information about the file you should see this: 

You can make this routine more generic so that any MIME types can be handled.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get article updates : Facebook  Twitter  LinkedIn

Posted On : 13 January 2020


Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates