从 1.4.0 Beta 版开始,可续传媒体下载已成为 Google API .NET 客户端库中的一项功能。Google API 专用库包含可与此功能进行交互的便捷方法。
可续传媒体下载协议与可续传媒体上传协议类似,后者可在 Drive API 的媒体上传页面查看。
感兴趣的主类是 MediaDownloader
。在可续传媒体下载的这种实现中,媒体内容以分块的形式下载(分块大小可配置)。
示例代码
如果 API 专属库中的方法包含发现文档中的“supportsMediaDownload
”参数,则请求类中提供 Download
和 DownloadAsync
便捷方法。这些方法会将媒体数据下载到您提供的 Stream
对象中。例如:
{ // Create the service using the client credentials. var storageService = new StorageService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "APP_NAME_HERE" }); // Get the client request object for the bucket and desired object. var getRequest = storageService.Objects.Get("BUCKET_HERE", "OBJECT_HERE"); using (var fileStream = new System.IO.FileStream( "FILE_PATH_HERE", System.IO.FileMode.Create, System.IO.FileAccess.Write)) { // Add a handler which will be notified on progress changes. // It will notify on each chunk download and when the // download is completed or failed. getRequest.MediaDownloader.ProgressChanged += Download_ProgressChanged; getRequest.Download(fileStream); } } static void Download_ProgressChanged(IDownloadProgress progress) { Console.WriteLine(progress.Status + " " + progress.BytesDownloaded); }