当下载大文件时,如果网络不稳定或者程序异常退出,会导致下载失败,甚至重试多次仍无法完成下载。为此OSS提供了断点续传下载功能。
以下代码用于断点续传下载:
using Aliyun.OSS; using Aliyun.OSS.Common; var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; var objectName = "<yourObjectName>"; var localFilename = "<yourLocalFilename>"; var downloadFilename = "<yourDownloadFilename>"; var checkpointDir = "<yourCheckpointDir>"; // 创建OssClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { // 通过DownloadObjectRequest设置多个参数。 DownloadObjectRequest request = new DownloadObjectRequest(bucketName, objectName, downloadFilename) { // 指定下载的分片大小。 PartSize = 8 * 1024 * 1024, // 指定并发线程数。 ParallelThreadCount = 3, // checkpointDir用于保存断点续传进度信息。如果某一分片下载失败,再次下载时会根据文件中记录的点继续下载。如果checkpointDir为null,断点续传功能不会生效,每次失败后都会重新下载。 CheckpointDir = checkpointDir, }; // 断点续传下载。 client.ResumableDownloadObject(request); Console.WriteLine("Resumable download object:{0} succeeded", objectName); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); }
断点续传下载详情请参见断点续传下载。