Google Drive Api Asp.ne Core Uploading File
In some web-application nosotros may demand to upload files on Google Bulldoze, so in this post I accept explained how nosotros tin can employ Google Drive API and OAuth2 to upload whatsoever type of file on Google drive using ASP.NET MVC C#.
Create a new project in Visual Studio for ASP.NET MVC
Allow's begin by creating new projection in Visual Studio, navigate to File-> New -> Projection -> Select "ASP.NET web-application" from right pane and Select "Web" from left pane -> Enter project name ( GoogleDriveUploadMVC ) and Click "OK"
In Next Screen select "MVC" as template and so Click "OK"
Create new project in Google Developer Console
Earlier we move any farther with our MVC project, we need to create a new project in Google programmer console to become OAuth2 details.
Go to https://panel.developers.google.com/cloud-resources-manager
Click on "Create projection"
In the Next Screen, Enter project name and select Organization (if any applicable, default is No Orgnization) and Click "Create"
Once you accept created the project, you lot can open the Google Cloud platform dashboard ( https://console.cloud.google.com/home/dashboard ), it will open the recently created project by default, if not you can select the project from top left.
Once you have opened the dashboard, navigate to "API & services"-> "Dashboard"
At present, we need to enable "Google Drive API", so click on "Enable APIS and Services" and and so search for "Google Drive API" on next screen search box, once yous have selected "Google Drive API", enable it
Create OAuth Consent and Credentials
Once we have Enabled the Google Drive API, we need to create credentials, and save details OAuth Consent Screen.
Let's save details in OAuth Consent Screen, and enter the "Application Name" and salvage details
Now, we need to navigate to "Credentials" and create a new credentials for MVC application by Clicking on "Create Credentials" -> Select "OAuth Credentials" -> Select "Web awarding" -> Enter Name of application -> Enter "Auhtorised redirect URI" url properly otherwise you might get error ("400. That's an mistake. Error: redirect_uri_mismatch - Google OAuth Authentication")
Afterward creating it, you will the next screen, with client-clandestine and client-id, close it and download credentials in JSON format and save it in root directory of your projection.
Install Nuget package for Google Drive API in MVC application
Once nosotros have Client Id/Hush-hush from google developer console, we can go back to our MVC spider web-application and install Nuget package for Google Bulldoze API.
And so, navigate to "Tools"-> "Nuget Package Director" -> "Manage Nuget Packages for solution" -> Select "Browse" -> Search for "Google Drive API"
Create Google Drive API service class in MVC project
Once you have installed the Google API from Nuget, go to your project, right-click on Models folder and add a new class "GoogleDriveAPIHelper.cs", in this grade we volition initialize Google Drive API using Credentials created in above steps.
So, here is the code for "GoogleDriveAPIHelper.cs" to initialize service and upload files on information technology.
public course GoogleDriveAPIHelper { //add scope public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.Drive }; //create Bulldoze API service. public static DriveService GetService() { //get Credentials from client_secret.json file UserCredential credential; //Root Folder of projection var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/"); using (var stream = new FileStream(Path.Combine(CSPath, "client_secret_860319795502-th86n6pjkjmc53j0503u22j16a9r3c2r.apps.googleusercontent.com.json"), FileMode.Open up, FileAccess.Read)) { String FolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/"); ; Cord 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. DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GoogleDriveMVCUpload", }); return service; } //file Upload to the Google Bulldoze root folder. public static void UplaodFileOnDrive(HttpPostedFileBase file) { if (file != zero && file.ContentLength > 0) { //create service DriveService service = GetService(); string path = Path.Combine(HttpContext.Electric 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); 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(); } } } }
In the above Class we have 2 methods, one to upload file on bulldoze and another to initialize Google Drive Service using the Credentials in JSON downloaded from Google developer console for OAuth 2
You lot volition also need to create binder named "GoogleDriveFiles" in the root of your project, to upload user files there in your project.
Now go to your Alphabetize.cshtml view inside "Abode" Folder, and use the below Razor code to upload file
@{ ViewBag.Title = "Home Page"; } @using (Html.BeginForm("Index", "Dwelling house", FormMethod.Post, new { enctype = "multipart/grade-data" })) { <div grade="row" style="margin-top:10px;margin-lesser:10px;"> <div class="col-medico-two"><characterization for="file">Upload file on drive:</label></div> <div course="col-doc-x"> <input type="file" name="file" id="file" /> </div> <div class="col-doctor-ii"> <br/> <input type="submit" class="btn btn-success" value="Upload" /> </div> </div> } @ViewBag.Success
In your HomeController.cs, call the above created GoogleDriveHelper.cs class and upload file on google drive
using GoogleDriveUploadMVC.Models; using System.Web; using System.Web.Mvc; namespace GoogleDriveUploadMVC.Controllers { public grade HomeController : Controller { public ActionResult Alphabetize() { return View(); } [HttpPost] public ActionResult Alphabetize(HttpPostedFileBase file) { GoogleDriveAPIHelper.UplaodFileOnDrive(file); ViewBag.Success = "File Uploaded on Google Drive"; return View(); } } }
That's it, we are washed, now we can build and run the project in browser.
You lot will output every bit below
Note: Browser may inquire you to login into your account. Besides, you may get non authorised redirect URL mistake, if yes go to your OAuth Credentials page and enter correct Authorised URL.(400. That'south an mistake. Error: redirect_uri_mismatch - Google OAuth Authentication)
You lot will see uploaded file on your google drive.
That'due south it, we are done with uploading file on google drive. You can upload anytype of file on google drive by providing it'southward mimetype while uploading the file.
Few more google drive api helpful functions in C#
Nosotros are done with uploading function, here are few more than helpful functions using Google Drive API and C#
Listing all files of Google Bulldoze
//go all files from Google Drive. public static List<GoogleDriveFile> GetDriveFiles() { Google.Apis.Bulldoze.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(*)"; // Listing files. IList<Google.Apis.Drive.v3.Information.File> files = FileListRequest.Execute().Files; Listing<GoogleDriveFile> FileList = new List<GoogleDriveFile>(); // For getting only folders // files = files.Where(10 => ten.MimeType == "application/vnd.google-apps.folder").ToList(); if (files != cipher && 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 together(File); } } render FileList; }
For using in a higher place function you would accept to create another class "GoogleDriveFile.cs"
using System; using System.Collections.Generic; namespace GoogleDriveUploadMVC.Models { public class GoogleDriveFile { public cord Id { become; fix; } public long? Size { get; set up; } public string Name { get; set; } public long? Version { get; prepare; } public DateTime? CreatedTime { get; prepare; } public IList<cord> Parents { become; set; } public cord MimeType { get; set up; } } }
C# role for Downloading File From Google
//Download file from Google Bulldoze past fileId. public static string DownloadGoogleFile(string fileId) { DriveService service = GetService(); string FolderPath = HttpContext.Current.Server.MapPath("/GoogleDriveFiles/"); FilesResource.GetRequest asking = service.Files.Get(fileId); string FileName = asking.Execute().Proper name; string FilePath = 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 += (IDownloadProgress progress) => { switch (progress.Condition) { case DownloadStatus.Downloading: { Panel.WriteLine(progress.BytesDownloaded); suspension; } case DownloadStatus.Completed: { Panel.WriteLine("Download complete."); SaveStream(stream1, FilePath); break; } case DownloadStatus.Failed: { Panel.WriteLine("Download failed."); intermission; } } }; asking.Download(stream1); return FilePath; } // file save to server path private static void SaveStream(MemoryStream stream, cord FilePath) { using (FileStream file = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite)) { stream.WriteTo(file); } }
Creating Folder on Google Drive using C#
// Create Folder in root public static void CreateFolder(string FolderName) { DriveService service = GetService(); var FileMetaData = new Google.Apis.Drive.v3.Data.File(); FileMetaData.Name = FolderName; //this mimetype specify that we need folder in google drive FileMetaData.MimeType = "application/vnd.google-apps.binder"; FilesResource.CreateRequest asking; asking = service.Files.Create(FileMetaData); request.Fields = "id"; var file = request.Execute(); }
Basically in the to a higher place code nosotros are specifying FileMetaData.MimeType = "application/vnd.google-apps.binder" to create folder on Google Drive
Upload files inside binder
// File upload in existing folder public static void FileUploadInFolder(cord folderId, HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { //create service DriveService service = GetService(); //get file path string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"), Path.GetFileName(file.FileName)); file.SaveAs(path); //create file metadata var FileMetaData = new Google.Apis.Drive.v3.Data.File() { Proper name = Path.GetFileName(file.FileName), MimeType = MimeMapping.GetMimeMapping(path), //id of parent binder Parents = new Listing<string> { folderId } }; FilesResource.CreateMediaUpload request; //create stream and upload using (var stream = new System.IO.FileStream(path, Arrangement.IO.FileMode.Open up)) { asking = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType); request.Fields = "id"; request.Upload(); } var file1 = request.ResponseBody; } }
In the above lawmaking, the only difference from file upload version is that we are providing parent binder id, you can get all folders and it's id using below function
public static List<GoogleDriveFile> GetDriveFolders() { DriveService service = GetService(); List<GoogleDriveFile> FolderList = new List<GoogleDriveFile>(); FilesResource.ListRequest asking = service.Files.List(); request.Q = "mimeType='application/vnd.google-apps.folder'"; asking.Fields = "files(id, name)"; Google.Apis.Drive.v3.Data.FileList result = asking.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; }
These are most used functions of Google Bulldoze API in C#.
You tin download sample projection. Before using sample project, create your Google console projection and download credentials every bit explained higher up.
Y'all may also like to read:
Using Google Charts in ASP.NET MVC (With Example)
Showing Google Maps in ASP.NET MVC with Mark (Lat/Long data from database)
buntonjuserebeaven.blogspot.com
Source: https://qawithexperts.com/article/asp-net/upload-file-to-google-drive-using-google-drive-api-in-aspnet/236