Google Drive API v3 .NET: How to let users download files directly from the google drive and not from the server?

c# webforms google-drive-api

1093 观看


12 作者的声誉

I'm working on an 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:
                    case DownloadStatus.Completed:
                            Console.WriteLine("Download complete.");
                            SaveStream(stream, FilePath); //Save the file 
                    case DownloadStatus.Failed:
                            Console.WriteLine("Download failed.");

            return FilePath;

This is event handler in code behind:

protected void btnDownload_Click(object sender, EventArgs e)

        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));
    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.

作者: La Min Tun 的来源 发布者: 2017 年 12 月 27 日

回应 (1)


12710 作者的声誉


Downloading the file directly from browser would be to use the webContentLink.

A link for downloading the content of the file in a browser. This is only available for files with binary content in Drive."

Apparently, you're using ASP but I'll just share a snippet on how I do it with JS when I use the Drive Picker:

 function downloadImage(data) {
      if (data.action == google.picker.Action.PICKED) {
        var fileId =[0].id;
        //for images
        // var webcontentlink = ''+fileId+'&export=download'

        var webcontentlink = ''+fileId+'&export=download' webcontentlink,'image/png');
作者: noogui 发布者: 28.12.2017 03:23