ASP.NET MVC

Google Drive Integration In ASP.NET MVC

Introduction

In this article, we learn how to integrate Google Drive API in MVC Project and use the function for upload file, create folder, upload file in folder, move files, rename files or folders, create folder within another folder, get all files, get files from a specific folder, delete files, etc.,

Step 1: Login your Google account.

Step 2: Register your application in Google API Console from https://console.developers.google.com/start/api?id=drive this URL.

 

Step 3: Click on Continue button

Step 4:  click on the cancel button

 

Step 5: click on “OAuth consent screen” tab.

Step 6: Enter the Application name and click on the save button.

Step 7: now go to on Credentials and click on OAuth client ID.

 

Step 8:  select Web Application and click on Create button.

 

Step 9: download the OAuth 2.0 Client Id’s file, this file includes Client ID, Client secret id, project_id, auth_uri, token_uri, redirect_uris.

 

Step 10: Copy this file into the root folder of your project. Now right click on this file and go to the property and Select “Copy always” in Copy to Output Directory option.

 

Step 11: install the nugget package

Install this two NuGet package from nugget package manager.

(1)  Install-Package Google.Apis.Drive.v3

(2)  Install-Package Google.Apis.Drive.v2

 

Step 12:  Write this code to get permission for our application.

give the path where you want to save the Access token file

 

Step 13:  Create a Method for getting all drive files, folders, download files, delete files, Move Files. Rename File, Upload files in a folder, Create a folder in another folder, etc.,

using Google.Apis.Auth.OAuth2;
using Google.Apis.Download;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;

namespace DriveApi.Models
{
    public class GoogleDriveFilesRepository
    {
        public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.Drive};

        //create Drive API service.
        public static Google.Apis.Drive.v3.DriveService GetService()
        {
            //get Credentials from client_secret.json file 
            UserCredential credential;
            var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");

            using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                String FolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/"); ;
                String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");

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

            //create Drive API service.
            Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "GoogleDriveRestAPI-v3",
            });
            return service;
        }

        public static Google.Apis.Drive.v2.DriveService GetService_v2()
        {
            UserCredential credential;
            var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/");

            using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
            {
             
                String FilePath = Path.Combine(CSPath, "DriveServiceCredentials.json");

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

            //Create Drive API service.
            Google.Apis.Drive.v2.DriveService service = new Google.Apis.Drive.v2.DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "GoogleDriveRestAPI-v2",
            });
            return service;
        }

        //get all files from Google Drive.
        public static List<GoogleDriveFile> GetDriveFiles()
        {
            Google.Apis.Drive.v3.DriveService service = GetService();

            // Define parameters of request.
            Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();
           // for getting folders only.
            //FileListRequest.Q = "mimeType='application/vnd.google-apps.folder'";
            FileListRequest.Fields = "nextPageToken, files(*)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
            List<GoogleDriveFile> FileList = new List<GoogleDriveFile>();


            // For getting only folders
           // files = files.Where(x => x.MimeType == "application/vnd.google-apps.folder").ToList();


            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    GoogleDriveFile File = new GoogleDriveFile
                    {
                        Id = file.Id,
                        Name = file.Name,
                        Size = file.Size,
                        Version = file.Version,
                        CreatedTime = file.CreatedTime,
                        Parents = file.Parents,
                        MimeType = file.MimeType
                    };
                    FileList.Add(File);
                }
            }
            return FileList;
        }

        //file Upload to the Google Drive root folder.
        public static void FileUpload(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                Google.Apis.Drive.v3.DriveService service = GetService();

                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
                Path.GetFileName(file.FileName));
                file.SaveAs(path);

                var FileMetaData = new Google.Apis.Drive.v3.Data.File();
                FileMetaData.Name = Path.GetFileName(file.FileName);
                FileMetaData.MimeType = MimeMapping.GetMimeMapping(path);

                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;

                using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }


                // Create Folder in Drive
                
                
            }
        }

        //Download file from Google Drive by fileId.
        public static string DownloadGoogleFile(string fileId)
        {
            Google.Apis.Drive.v3.DriveService service = GetService();

            string FolderPath = System.Web.HttpContext.Current.Server.MapPath("/GoogleDriveFiles/");
            Google.Apis.Drive.v3.FilesResource.GetRequest request = service.Files.Get(fileId);

            string FileName = request.Execute().Name;
            string FilePath = System.IO.Path.Combine(FolderPath, FileName);

            MemoryStream stream1 = new MemoryStream();

            // Add a handler which will be notified on progress changes.
            // It will notify on each chunk download and when the
            // download is completed or failed.
            request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
            {
                switch (progress.Status)
                {
                    case DownloadStatus.Downloading:
                        {
                            Console.WriteLine(progress.BytesDownloaded);
                            break;
                        }
                    case DownloadStatus.Completed:
                        {
                            Console.WriteLine("Download complete.");
                            SaveStream(stream1, FilePath);
                            break;
                        }
                    case DownloadStatus.Failed:
                        {
                            Console.WriteLine("Download failed.");
                            break;
                        }
                }
            };
            request.Download(stream1);
            return FilePath;
        }

        // file save to server path
        private static void SaveStream(MemoryStream stream, string FilePath)
        {
            using (System.IO.FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
            {
                stream.WriteTo(file);
            }
        }

        //Delete file from the Google drive
        public static void DeleteFile(GoogleDriveFile files)
        {
            Google.Apis.Drive.v3.DriveService service = GetService();
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");

                if (files == null)
                    throw new ArgumentNullException(files.Id);

                // Make the request.
                service.Files.Delete(files.Id).Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Files.Delete failed.", ex);
            }
        }
        
        public static List<GoogleDriveFile> GetContainsInFolder(String folderId)
        {
            List<string> ChildList = new List<string>();
            Google.Apis.Drive.v2.DriveService ServiceV2 = GetService_v2();
            ChildrenResource.ListRequest ChildrenIDsRequest = ServiceV2.Children.List(folderId);

            // for getting only folders
            //ChildrenIDsRequest.Q = "mimeType='application/vnd.google-apps.folder'";
            do
            {
                var children = ChildrenIDsRequest.Execute();

                if (children.Items != null && children.Items.Count > 0)
                {
                    foreach (var file in children.Items)
                    {
                        ChildList.Add(file.Id);
                    }
                }
                ChildrenIDsRequest.PageToken = children.NextPageToken;

            } while (!String.IsNullOrEmpty(ChildrenIDsRequest.PageToken));

            //Get All File List
            List<GoogleDriveFile> AllFileList = GetDriveFiles();
            List<GoogleDriveFile> Filter_FileList = new List<GoogleDriveFile>();

            foreach (string Id in ChildList)
            {
                Filter_FileList.Add(AllFileList.Where(x => x.Id == Id).FirstOrDefault());
            }
            return Filter_FileList;
        }

        // Create Folder in root
        public static void CreateFolder(string FolderName)
        {
            Google.Apis.Drive.v3.DriveService service = GetService();

            var FileMetaData = new Google.Apis.Drive.v3.Data.File();
            FileMetaData.Name = FolderName;
            FileMetaData.MimeType = "application/vnd.google-apps.folder";

            Google.Apis.Drive.v3.FilesResource.CreateRequest request;

            request = service.Files.Create(FileMetaData);
            request.Fields = "id";
            var file = request.Execute();
            Console.WriteLine("Folder ID: " + file.Id);
        }

        // Create Folder in existing folder
        public static void CreateFolderInFolder(string folderId, string FolderName)
        {

            Google.Apis.Drive.v3.DriveService service = GetService();

            var FileMetaData = new Google.Apis.Drive.v3.Data.File()
            {
                Name = Path.GetFileName(FolderName),
                MimeType = "application/vnd.google-apps.folder",
                Parents = new List<string>
                    {
                        folderId
                    }
            };

            
            Google.Apis.Drive.v3.FilesResource.CreateRequest request;

            request = service.Files.Create(FileMetaData);
            request.Fields = "id";
            var file = request.Execute();
            Console.WriteLine("Folder ID: " + file.Id);

            var file1 = request;

        }

        // File upload in existing folder
        public static void FileUploadInFolder(string folderId, HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                Google.Apis.Drive.v3.DriveService service = GetService();

                string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
                Path.GetFileName(file.FileName));
                file.SaveAs(path);

                var FileMetaData = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = Path.GetFileName(file.FileName),
                    MimeType = MimeMapping.GetMimeMapping(path),
                    Parents = new List<string>
                    {
                        folderId
                    }
                };

                Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
                using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
                {
                    request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                    request.Fields = "id";
                    request.Upload();
                }
                var file1 = request.ResponseBody;
            }
        }
        

        // check Folder name exist or note in root
        public static bool CheckFolder(string FolderName)
        {
            bool IsExist = false;
            
            Google.Apis.Drive.v3.DriveService service = GetService();
            
            // Define parameters of request.
            Google.Apis.Drive.v3.FilesResource.ListRequest FileListRequest = service.Files.List();
            FileListRequest.Fields = "nextPageToken, files(*)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = FileListRequest.Execute().Files;
            List<GoogleDriveFile> FileList = new List<GoogleDriveFile>();


            //For getting only folders
             files = files.Where(x => x.MimeType == "application/vnd.google-apps.folder" && x.Name== FolderName).ToList();
            
            if (files.Count > 0)
            {
                IsExist = false;    
            }
            return IsExist;
        }


        public static List<GoogleDriveFile> GetDriveFolders()
        {
            Google.Apis.Drive.v3.DriveService service = GetService();
            List<GoogleDriveFile> FolderList = new List<GoogleDriveFile>();

            Google.Apis.Drive.v3.FilesResource.ListRequest request = service.Files.List();
            request.Q = "mimeType='application/vnd.google-apps.folder'";
            request.Fields = "files(id, name)";

            Google.Apis.Drive.v3.Data.FileList result = request.Execute();
            foreach (var file in result.Files)
            {
                GoogleDriveFile File = new GoogleDriveFile
                {
                    Id = file.Id,
                    Name = file.Name,
                    Size = file.Size,
                    Version = file.Version,
                    CreatedTime = file.CreatedTime
                };
                FolderList.Add(File);
            }
            return FolderList;
        }

        public static string MoveFiles(String fileId, String folderId)
        {
            Google.Apis.Drive.v3.DriveService service = GetService();

            // Retrieve the existing parents to remove
            Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId);
            getRequest.Fields = "parents";
            Google.Apis.Drive.v3.Data.File file = getRequest.Execute();
            string previousParents = String.Join(",", file.Parents);

            // Move the file to the new folder
            Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);
            updateRequest.Fields = "id, parents";
            updateRequest.AddParents = folderId;
            updateRequest.RemoveParents = previousParents;

            file = updateRequest.Execute();
            if (file != null)
            {
                return "Success";
            }
            else
            {
                return "Fail";
            }
        }
        public static string CopyFiles(String fileId, String folderId)
        {
            Google.Apis.Drive.v3.DriveService service = GetService();

            // Retrieve the existing parents to remove
            Google.Apis.Drive.v3.FilesResource.GetRequest getRequest = service.Files.Get(fileId);
            getRequest.Fields = "parents";
            Google.Apis.Drive.v3.Data.File file = getRequest.Execute();

            // Copy the file to the new folder
            Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);
            updateRequest.Fields = "id, parents";
            updateRequest.AddParents = folderId;
            //updateRequest.RemoveParents = previousParents;
            file = updateRequest.Execute();
            if (file != null)
            {
                return "Success";
            }
            else
            {
                return "Fail";
            }
        }

        private static void RenameFile(String fileId, String newTitle)
        {
            try
            {
                Google.Apis.Drive.v2.DriveService service = GetService_v2();

                Google.Apis.Drive.v2.Data.File file = new Google.Apis.Drive.v2.Data.File();
                file.Title = newTitle;

                // Rename the file.
                Google.Apis.Drive.v2.FilesResource.PatchRequest request = service.Files.Patch(file, fileId);
                Google.Apis.Drive.v2.Data.File updatedFile = request.Execute();

                //return updatedFile;
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
                //return null;
            }
        }

    }
}

 

Step 14: Call the above method from the controller.

using DriveApi.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DriveApi.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult GetGoogleDriveFiles()
        {
            return View(GoogleDriveFilesRepository.GetDriveFiles());
        }
        
       
        [HttpPost]
        public ActionResult DeleteFile(GoogleDriveFile file)
        {
            GoogleDriveFilesRepository.DeleteFile(file);
            return RedirectToAction("GetGoogleDriveFiles");
        }

        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase file)
        {
            GoogleDriveFilesRepository.FileUpload(file);
            return RedirectToAction("GetGoogleDriveFiles");
        }

        public void DownloadFile(string id)
        {
            string FilePath = GoogleDriveFilesRepository.DownloadGoogleFile(id);
                
            Response.ContentType = "application/zip";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FilePath));
            Response.WriteFile(System.Web.HttpContext.Current.Server.MapPath("~/GoogleDriveFiles/" + Path.GetFileName(FilePath)));
            Response.End();
            Response.Flush();
        }
        

        [HttpGet]
        public ActionResult GetContainsInFolder(string folderId)
        {
            return View(GoogleDriveFilesRepository.GetContainsInFolder(folderId));
        }

        [HttpPost]
        public ActionResult CreateFolder(String FolderName)
        {
            GoogleDriveFilesRepository.CreateFolder(FolderName);
            return RedirectToAction("GetGoogleDriveFiles1");
        }

        
        [HttpPost]
        public ActionResult FileUploadInFolder(GoogleDriveFile FolderId, HttpPostedFileBase file)
        {
            GoogleDriveFilesRepository.FileUploadInFolder(FolderId.Id, file);
            return RedirectToAction("GetGoogleDriveFiles1");
        }
        

        [HttpGet]
        public JsonResult FolderLists()
        {
            List<GoogleDriveFile> AllFolders = GoogleDriveFilesRepository.GetDriveFolders();
            List<DDLOptions> obj = new List<DDLOptions>();

            foreach (GoogleDriveFile EachFolder in AllFolders)
            {
                obj.Add(new DDLOptions { Id = EachFolder.Id, Name = EachFolder.Name });
            }
            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        public string MoveFiles(String fileId, String folderId)
        {
            string Result = GoogleDriveFilesRepository.MoveFiles(fileId, folderId);
            return Result;
        }

        public string CopyFiles(String fileId, String folderId)
        {
            string Result = GoogleDriveFilesRepository.CopyFiles(fileId, folderId);
            return Result;
        }

        public JsonResult Render_GetGoogleDriveFilesView()
        {
            Dictionary<string, object> jsonResult = new Dictionary<string, object>();
            var result = GoogleDriveFilesRepository.GetDriveFiles();
            jsonResult.Add("Html", RenderRazorViewToString("~/Views/Home/GetGoogleDriveFiles1.cshtml", result));
            return Json(jsonResult, JsonRequestBehavior.AllowGet);
        }

        public string RenderRazorViewToString(string viewName, object model)
        {
            if (model != null)
            {
                ViewData.Model = model;

            }
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }
    }
}

Step 15: Copy below code and paste into your view code.

@model IEnumerable<DriveApi.Models.GoogleDriveFile>
@{
    ViewBag.Title = "GetGoogleDriveFiles";
}

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<style type="text/css">
    #header {
        width: 100%;
        background-color: #CCCCCC;
        text-align: center;
    }

    #layouttable {
        border: 0px;
        width: 100%;
        font-family: 'Segoe UI';
    }

        #layouttable td.col1 {
            width: 20%;
            vertical-align: top;
        }

        #layouttable td.col2 {
            width: 60%;
            vertical-align: top;
            background-color: #E8E8E8;
        }

        #layouttable td.col3 {
            width: 20%;
            vertical-align: top;
        }
</style>

<center>


    @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <div class="row" style="margin-top:10px;margin-bottom:10px;">
            <div class="col-md-2"><label for="file">Upload file:</label></div>

            <div class="col-md-2">
                <input type="file" name="file" id="file" />
            </div>
            <div class="col-md-2"> 
                <input type="submit" class="btn btn-success" value="Upload" />
            </div>
        </div>
    }


    <table class="table" border="1">
        <tr id="header">
            <th>
                <label>Created Date</label>
            </th>
            <th>
                <label>Name</label>
            </th>
            <th>
                <label>Type</label>
            </th>
            <th>
                <label>Size</label>
            </th>

            <th>
                Action
            </th>
        </tr>

        @if (Model.Count() > 0)
        {
            foreach (var item in Model)
            {
                <tr id="layouttable">
                    <td>
                        @string.Format("{0: dd/MM/yyyy}", Convert.ToDateTime(item.CreatedTime))
                    </td>
                    <td>
                        @item.Name
                    </td>
                    <td>
                        @item.MimeType
                    </td>
                    <td>
                        @{
                            long? KiloByte = @item.Size / 1024;
                            string NewSize = KiloByte + " KB";
                        }
                        @NewSize
                    </td>

                    <td>
                        <a class="btn btn-primary" href="/Home/DownloadFile/@item.Id">Download</a>
                        @using (Html.BeginForm("DeleteFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
                        {
                            <input type="hidden" name=Id value="@item.Id">
                            <input type="submit" class="DeleteFile btn btn-danger" value="Delete" style="align-content:center;margin-top:5px;" />
                        }

                    </td>
                </tr>
             }
           }
          else
          {
                <td colspan="6">No files found</td>
          }

    </table>

</center>

<script>
    $(document).on('click', '.DownloadFile', function (fileId) {
        var fileId = $(this).attr("data-key");
        window.location.href = '/Home/DownloadFile/' + fileId;
    });
</script>

 

Output :

 

You can download the source code from here

 

Kaushik Dudhat

Hi All, I am Kaushik Dudhat. I'm Working as a Web Developer. I have strong technical skills as well as excellent interpersonal skills. I am eager to be challenged in order to grow and improve my communication and professional IT skills gained through previous experiences in the IT sector. I have extensive experience with designing and developing enterprise scale applications. I have good skill of ASP.NET MVC, AngularJS, Web API, EPPlus, SQL, Entity Framework, Html, CSS, Bootstrap, JQuery, Rotativa and Windows services.

View Comments

Share
Published by
Kaushik Dudhat

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago