2017-12-27 455 views
0

我正在与谷歌驱动器api v3的asp.net网站上工作,仍然是一个新手。一切正常与谷歌驱动器API。但我并不满意目前我下载文件的方式。Google Drive API v3 .NET:如何让用户直接从谷歌驱动器下载文件而不是从服务器下载文件?

下面是示例代码:

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; 
    } 

这是代码的事件处理程序的背后:

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 
    } 
} 

因此,当用户请求下载从谷歌驱动器中的文件时,服务器将下载首先文件,然后将其传回给用户。我想知道是否有一种方法可以让用户直接从谷歌浏览器通过浏览器下载文件,而不是从服务器下载文件。如果没有,我想我应该删除用户下载后在服务器上下载的文件。请赐教。提前致谢。

回答

0

直接从浏览器下载文件将使用webContentLink

用于在浏览器中下载文件内容的链接。这是 仅适用于在驱动器的二进制内容文件“

显然,你使用的ASP,但我只想分享我如何与JS做一个片段,当我使用驱动器选取器:

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

     var webcontentlink = ' https://docs.google.com/uc?id='+fileId+'&export=download' 
     window.open(webcontentlink,'image/png'); 
     } 
    } 
+0

感谢您的回答,我只知道如何得到的东西与谷歌驱动API在C#中工作,并且有有点非常有限的网络资源或样品去学习v3的,我可以看到一个完整的工作示例代码,其中包括通过客户端密码和访问令牌获取Google服务,并下载文件? –