2017-12-27 457 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服務,並下載文件? –