C# Google Drive API v3.NET:如何让用户直接从Google Drive而不是从服务器下载文件?
我正在使用google drive api v3开发一个asp.net网站,还是个新手。一切都与谷歌驱动器api配合得很好。但我对目前下载文件的方式并不满意 以下是示例代码:C# Google Drive API v3.NET:如何让用户直接从Google Drive而不是从服务器下载文件?,c#,asp.net,webforms,google-drive-api,C#,Asp.net,Webforms,Google Drive Api,我正在使用google drive api v3开发一个asp.net网站,还是个新手。一切都与谷歌驱动器api配合得很好。但我对目前下载文件的方式并不满意 以下是示例代码: public static string DownloadGoogleFile(string fileId) { DriveService service = GetService(); //Get google drive service FilesReso
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
}
}
因此,当用户请求从谷歌硬盘下载文件时,服务器将首先下载文件,然后将其传输回用户。我想知道是否有一种方法可以让用户通过浏览器直接从谷歌硬盘而不是服务器下载文件。如果没有,我想我应该在用户下载后删除服务器上的下载文件。请开导我。提前多谢。直接从浏览器下载文件将使用 用于在浏览器中下载文件内容的链接。这是 仅适用于驱动器中包含二进制内容的文件。“ 显然,您使用的是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');
}
}
谢谢你的回答。我只知道如何在c#中使用google drive api。而且v3的在线资源或示例非常有限。我可以看看完整的工作示例代码吗,其中包括使用客户端密码和访问令牌获取google服务,以及下载文件?