【发布时间】:2017-12-27 16:59:48
【问题描述】:
我正在使用 google drive api v3 开发一个 asp.net 网站,但仍然是新手。谷歌驱动器 api 一切正常。但我对我目前下载文件的方式并不满意。
这里是示例代码:
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
}
}
因此,当用户请求从 google 驱动器下载文件时,服务器将首先下载文件,然后将其传输回用户。我想知道是否有一种方法可以让用户通过浏览器直接从谷歌驱动器而不是从服务器下载文件。如果没有,我想我应该在用户下载后删除服务器上下载的文件。请赐教。提前非常感谢。
【问题讨论】:
标签: c# asp.net webforms google-drive-api