I'm working on an asp.net website with google drive api v3 and still a newbie. Everything is working well with the google drive api. But I'm not really happy with my current way of downloading files.
Here is the sample code:
public static string DownloadGoogleFile(string fileId)
{
DriveService service = GetService(); //Get google drive service
FilesResource.GetRequest request = service.Files.Get(fileId);
string FileName = request.Execute().Name;
string FilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Downloads"),FileName);
MemoryStream stream = new MemoryStream();
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(stream, FilePath); //Save the file
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request.Download(stream);
return FilePath;
}
This is event handler in code behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string id = TextBox3.Text.Trim();
string FilePath = google_drive.DownloadGoogleFile(id);
HttpContext.Current.Response.ContentType = MimeMapping.GetMimeMapping(FilePath);
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(FilePath));
//HttpContext.Current.Response.WriteFile(FilePath);
HttpContext.Current.Response.TransmitFile(FilePath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception ex)
{
//Handle Exception
}
}
So when a user request to download a file from the google drive, server will download the file first and then transfer it back to the user. I'm wondering if there is a way we can let the users download files through a browser directly from the google drive and not from the server. And if there's not, I think I should delete downloaded files on the server after users downloaded. Please enlighten me. Thanks a lot in advance.