Lorsque vous téléchargez un objet de plus de 5 Go depuis Object Storage Service (OSS) vers votre ordinateur local, des interruptions réseau ou des plantages peuvent empêcher la réussite de l'opération. Si plusieurs tentatives échouent, utilisez le téléchargement avec reprise. Cette méthode divise l'objet en plusieurs parties et les télécharge en parallèle pour accélérer le processus. La progression du téléchargement est enregistrée dans un fichier de point de contrôle (checkpoint). En cas d'échec du téléchargement d'une partie, la reprise s'effectue à partir de la position enregistrée dans ce fichier. Une fois toutes les parties téléchargées, elles sont assemblées pour reconstituer l'objet complet.
Prérequis
Téléchargement d'objets Archive : les objets Archive doivent être restaurés ou l'accès en temps réel aux objets Archive doit être activé pour le bucket qui les stocke. Pour plus d'informations, consultez les rubriques Restaurer des objets et Lecture directe des archives.
Téléchargement d'objets Cold Archive ou Deep Cold Archive : les objets Cold Archive ou Deep Cold Archive doivent être restaurés. Pour plus d'informations, consultez la rubrique Restaurer des objets.
Notes d'utilisation
Le téléchargement avec reprise est disponible uniquement via les SDK OSS. Tenez compte des points suivants lors de son utilisation :
Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Si vous accédez à OSS depuis d'autres services Alibaba Cloud situés dans la même région, privilégiez un endpoint interne. Pour obtenir la liste des régions et des endpoints OSS, consultez la rubrique Régions et endpoints.
Les identifiants d'accès utilisés dans cette rubrique sont récupérés depuis des variables d'environnement. Pour savoir comment configurer ces identifiants, consultez la rubrique Configurer les identifiants d'accès.
Les exemples de code illustrent la création d'une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants temporaires du Security Token Service (STS), reportez-vous à la rubrique Configurer un client (SDK Go V1).
L'autorisation
oss:GetObjectest requise pour utiliser le téléchargement avec reprise. Pour plus d'informations, consultez la rubrique Accorder une politique personnalisée.Les SDK OSS enregistrent la progression du téléchargement dans un fichier de point de contrôle. Assurez-vous de disposer des droits d'écriture sur ce fichier.
Ne modifiez pas la somme de contrôle contenue dans le fichier de point de contrôle. Si ce fichier est endommagé, vous devez retélécharger toutes les parties.
Si la valeur ETag de l'objet change ou si des parties sont perdues ou modifiées pendant le téléchargement, vous devez recommencer le téléchargement de l'objet entier.
Utiliser les SDK OSS
Les exemples de code suivants montrent comment effectuer un téléchargement avec reprise à l'aide des SDK OSS pour les langages de programmation courants. Pour découvrir la mise en œuvre dans d'autres langages, consultez la rubrique Présentation.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
public class Demo {
public static void main(String[] args) throws Exception {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
String objectName = "exampledir/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Perform resumable download in which 10 parts can be concurrently downloaded.
DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, objectName);
// Specify the full path to which you want to download the object. Example: D:\\localpath\\examplefile.txt.
downloadFileRequest.setDownloadFile("D:\\localpath\\examplefile.txt");
// Specify the part size. Unit: bytes. Valid values: 100 KB to 5 GB. The default part size is 100 KB.
downloadFileRequest.setPartSize(1 * 1024 * 1024);
// Specify the number of concurrent threads for the resumable download task. Default value: 1.
downloadFileRequest.setTaskNum(10);
// Specify whether to enable resumable download. By default, resumable download is disabled.
downloadFileRequest.setEnableCheckpoint(true);
// Specify the full path of the checkpoint file. Example: D:\\localpath\\examplefile.txt.dcp.
// The checkpoint file is generated when the download is interrupted. If you want to resume the download task, you must specify the full path of the checkpoint file. After the object is downloaded, the checkpoint file is deleted.
//downloadFileRequest.setCheckpointFile("D:\\localpath\\examplefile.txt.dcp");
// Download the object.
DownloadFileResult downloadRes = ossClient.downloadFile(downloadFileRequest);
// After the object is downloaded, the object metadata is returned.
ObjectMetadata objectMetadata = downloadRes.getObjectMetadata();
System.out.println(objectMetadata.getETag());
System.out.println(objectMetadata.getLastModified());
System.out.println(objectMetadata.getUserMetadata().get("meta"));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}import argparse
import os
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser and describe the purpose of the script: download file sample.
parser = argparse.ArgumentParser(description="download file sample")
# Add the command-line argument --region, which indicates the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the command-line argument --bucket, which indicates the name of the bucket from which you want to download the file. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the command-line argument --endpoint, which indicates the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the command-line argument --key, which indicates the key of the object (file) in OSS. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the command-line argument --file_path, which indicates the local path to save the downloaded file. This argument is required. For example, "/Users/yourLocalPath/yourFileName".
parser.add_argument('--file_path', help='The path to save the downloaded file.', required=True)
def main():
# Parse the command-line arguments to obtain the values entered by the user.
args = parser.parse_args()
# Load the authentication information required to access OSS from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configurations of the SDK to create a configuration object and set the authentication provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region property of the configuration object based on the command-line arguments provided by the user.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property of the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configurations to initialize the OSS client to interact with OSS.
client = oss.Client(cfg)
# Create an object for downloading files and set advanced options.
downloader = client.downloader(
use_temp_file=True, # Use a temporary file.
enable_checkpoint=True, # Enable resumable download.
checkpoint_dir=os.path.dirname(args.file_path), # The directory to save the resumable download record file.
verify_data=True # Specifies whether to verify data.
)
# Call the method to perform the file download operation.
result = downloader.download_file(
oss.GetObjectRequest(
bucket=args.bucket, # Specify the destination bucket.
key=args.key, # Specify the name of the file in OSS.
),
filepath=args.file_path # Specify the local path to save the downloaded file.
)
# Print information about the download result, including the number of bytes written.
print(f'written: {result.written}')
# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
main() # The entry point of the script, where the program flow starts.package main
import (
"context"
"flag"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Use the init function to initialize parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "src-object", "", "The name of the source object.")
}
func main() {
// Parse parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the source object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, src object name required")
}
// Create an OSS client configuration.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a Downloader.
d := client.NewDownloader()
// Create a request to download the object.
request := &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
}
// The path of the local file.
localFile := "local-file"
// Specify downloader options.
downloaderOptions := func(do *oss.DownloaderOptions) {
do.EnableCheckpoint = true // Enable checkpoint recording.
do.CheckpointDir = "./checkpoint" // Specify the path of the checkpoint file.
do.UseTempFile = true // Specify the use of a temporary file.
}
// Execute the request to download the object.
result, err := d.DownloadFile(context.TODO(), request, localFile, downloaderOptions)
if err != nil {
log.Fatalf("failed to download file %v", err)
}
// Print the success response.
log.Printf("download file %s to local-file successfully, size: %d", objectName, result.Written)
}
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
// Download the object to a local file named examplefile.txt and save it to the specified local path (D:\\localpath). If the local file exists, it is overwritten. If the local file does not exist, it is created.
// If you do not specify a local path, the downloaded file is saved to the local path of the project where the sample program resides.
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Specify the full path of the breakpoint record file. Example: D:\\localpath\\examplefile.txt.dcp.
// You need to specify the breakpoint record file only when the download is interrupted and a breakpoint record file is generated. After the download is complete, this file is deleted.
var checkpointDir = "D:\\localpath\\examplefile.txt.dcp";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Set the signature version to V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Set multiple parameters in DownloadObjectRequest.
DownloadObjectRequest request = new DownloadObjectRequest(bucketName, objectName, downloadFilename)
{
// Specify the size of each shard for download in bytes.
PartSize = 8 * 1024 * 1024,
// Specify the number of concurrent threads.
ParallelThreadCount = 3,
// checkpointDir is used to save the progress of the resumable download. If a shard fails to download, the download resumes from the recorded breakpoint when you try again. If checkpointDir is set to null, the resumable download feature is disabled. The download restarts from the beginning after each failure.
CheckpointDir = checkpointDir,
};
// Perform a resumable download.
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);
}#import "DownloadService.h"
#import "OSSTestMacros.h"
@implementation DownloadRequest
@end
@implementation Checkpoint
- (instancetype)copyWithZone:(NSZone *)zone {
Checkpoint *other = [[[self class] allocWithZone:zone] init];
other.etag = self.etag;
other.totalExpectedLength = self.totalExpectedLength;
return other;
}
@end
@interface DownloadService()<NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@property (nonatomic, strong) NSURLSession *session; // Network session.
@property (nonatomic, strong) NSURLSessionDataTask *dataTask; // Data request task.
@property (nonatomic, copy) DownloadFailureBlock failure; // Called on request failure.
@property (nonatomic, copy) DownloadSuccessBlock success; // Called on request success.
@property (nonatomic, copy) DownloadProgressBlock progress; // Tracks download progress.
@property (nonatomic, copy) Checkpoint *checkpoint; // The checkpoint.
@property (nonatomic, copy) NSString *requestURLString; // The URL of the resource to download.
@property (nonatomic, copy) NSString *headURLString; // The URL for the HEAD request.
@property (nonatomic, copy) NSString *targetPath; // The local path to store the file.
@property (nonatomic, assign) unsigned long long totalReceivedContentLength; // The size of the content received so far.
@property (nonatomic, strong) dispatch_semaphore_t semaphore;
@end
@implementation DownloadService
- (instancetype)init
{
self = [super init];
if (self) {
NSURLSessionConfiguration *conf = [NSURLSessionConfiguration defaultSessionConfiguration];
conf.timeoutIntervalForRequest = 15;
NSOperationQueue *processQueue = [NSOperationQueue new];
_session = [NSURLSession sessionWithConfiguration:conf delegate:self delegateQueue:processQueue];
_semaphore = dispatch_semaphore_create(0);
_checkpoint = [[Checkpoint alloc] init];
}
return self;
}
// DownloadRequest is the core of the download logic.
+ (instancetype)downloadServiceWithRequest:(DownloadRequest *)request {
DownloadService *service = [[DownloadService alloc] init];
if (service) {
service.failure = request.failure;
service.success = request.success;
service.requestURLString = request.sourceURLString;
service.headURLString = request.headURLString;
service.targetPath = request.downloadFilePath;
service.progress = request.downloadProgress;
if (request.checkpoint) {
service.checkpoint = request.checkpoint;
}
}
return service;
}
/**
* Gets file information by using the HEAD method and compares the file's ETag with the one in the local checkpoint.
*/
- (BOOL)getFileInfo {
__block BOOL resumable = NO;
NSURL *url = [NSURL URLWithString:self.headURLString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"HEAD"];
// Process object information. For example, the ETag is used for pre-checks in resumable downloads, and content-length is used to calculate download progress.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"Failed to get file metadata. Error: %@", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSString *etag = [httpResponse.allHeaderFields objectForKey:@"Etag"];
if ([self.checkpoint.etag isEqualToString:etag]) {
resumable = YES;
} else {
resumable = NO;
}
}
dispatch_semaphore_signal(self.semaphore);
}];
[task resume];
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
return resumable;
}
/**
* Gets the size of the local file.
*/
- (unsigned long long)fileSizeAtPath:(NSString *)filePath {
unsigned long long fileSize = 0;
NSFileManager *dfm = [NSFileManager defaultManager];
if ([dfm fileExistsAtPath:filePath]) {
NSError *error = nil;
NSDictionary *attributes = [dfm attributesOfItemAtPath:filePath error:&error];
if (!error && attributes) {
fileSize = attributes.fileSize;
} else if (error) {
NSLog(@"error: %@", error);
}
}
return fileSize;
}
- (void)resume {
NSURL *url = [NSURL URLWithString:self.requestURLString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"GET"];
BOOL resumable = [self getFileInfo]; // A `NO` return value indicates that the conditions for a resumable download are not met.
if (resumable) {
self.totalReceivedContentLength = [self fileSizeAtPath:self.targetPath];
NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", self.totalReceivedContentLength];
[request setValue:requestRange forHTTPHeaderField:@"Range"];
} else {
self.totalReceivedContentLength = 0;
}
if (self.totalReceivedContentLength == 0) {
[[NSFileManager defaultManager] createFileAtPath:self.targetPath contents:nil attributes:nil];
}
self.dataTask = [self.session dataTaskWithRequest:request];
[self.dataTask resume];
}
- (void)pause {
[self.dataTask cancel];
self.dataTask = nil;
}
- (void)cancel {
[self.dataTask cancel];
self.dataTask = nil;
[self removeFileAtPath: self.targetPath];
}
- (void)removeFileAtPath:(NSString *)filePath {
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:self.targetPath error:&error];
if (error) {
NSLog(@"remove file with error : %@", error);
}
}
#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
// Determines if the download is complete and reports the result to the upper-layer service.
didCompleteWithError:(nullable NSError *)error {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if ([httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
if (httpResponse.statusCode == 200) {
self.checkpoint.etag = [[httpResponse allHeaderFields] objectForKey:@"Etag"];
self.checkpoint.totalExpectedLength = httpResponse.expectedContentLength;
} else if (httpResponse.statusCode == 206) {
self.checkpoint.etag = [[httpResponse allHeaderFields] objectForKey:@"Etag"];
self.checkpoint.totalExpectedLength = self.totalReceivedContentLength + httpResponse.expectedContentLength;
}
}
if (error) {
if (self.failure) {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:error.userInfo];
[userInfo oss_setObject:self.checkpoint forKey:@"checkpoint"];
NSError *tError = [NSError errorWithDomain:error.domain code:error.code userInfo:userInfo];
self.failure(tError);
}
} else if (self.success) {
self.success(@{@"status": @"success"});
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)dataTask.response;
if ([httpResponse isKindOfClass:[NSHTTPURLResponse class]]) {
if (httpResponse.statusCode == 200) {
self.checkpoint.totalExpectedLength = httpResponse.expectedContentLength;
} else if (httpResponse.statusCode == 206) {
self.checkpoint.totalExpectedLength = self.totalReceivedContentLength + httpResponse.expectedContentLength;
}
}
completionHandler(NSURLSessionResponseAllow);
}
// Appends the received data to the file and updates the download progress.
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.targetPath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
self.totalReceivedContentLength += data.length;
if (self.progress) {
self.progress(data.length, self.totalReceivedContentLength, self.checkpoint.totalExpectedLength);
}
}
@end#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize OSS account information. */
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the Region ID of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region ID to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name, for example, examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Download the object to a local file named examplefile.txt and save it to the specified local path (D:\\localpath). If the local file exists, it is overwritten. If it does not exist, it is created. */
/* If you do not specify a local path, the downloaded file is saved to the local path of the project by default. */
std::string DownloadFilePath = "D:\\localpath\\examplefile.txt";
/* Set the folder for the breakpoint record file and make sure the specified folder exists, for example, D:\\localpath. */
/* If an object download is interrupted and a breakpoint record file is generated, you must set the corresponding breakpoint record file to resume the download. After the download is complete, this file is deleted. */
std::string CheckpointDir = "D:\\localpath";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this code sample, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Perform a resumable download. */
DownloadObjectRequest request(BucketName, ObjectName, DownloadFilePath, CheckpointDir);
auto outcome = client.ResumableDownloadObject(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "ResumableDownloadObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}#include "oss_api.h"
#include "aos_http_io.h"
/* Replace yourEndpoint with the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Replace with your bucket name, for example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the full path of the local file. */
const char *local_filename = "yourLocalFilename";
/* Replace yourRegion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize the aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// You must also configure the following two parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a CNAME is used. A value of 0 indicates that no CNAME is used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* A memory pool (pool) for memory management, which is equivalent to apr_pool_t. The implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object;
aos_string_t file;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
oss_resumable_clt_params_t *clt_params;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
aos_str_set(&file, local_filename);
/* Perform a resumable download. */
clt_params = oss_create_resumable_clt_params_content(pool, 1024 * 100, 3, AOS_TRUE, NULL);
resp_status = oss_resumable_download_file(oss_client_options, &bucket, &object, &file, headers, NULL, clt_params, NULL, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("download succeeded\n");
} else {
printf("download failed\n");
}
/* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# The endpoint of China (Hangzhou) is used as an example. Specify the actual endpoint.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name, for example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Set key to the full path of the object. The full path cannot contain the bucket name. For example, exampledir/example.zip.
# Set file to the full path of the local file. For example, /tmp/example.zip.
bucket.resumable_download('exampledir/example.zip', '/tmp/example.zip') do |p|
puts "Progress: #{p}"
end
bucket.resumable_download(
'exampledir/example.zip', '/tmp/example.zip',
# Set cpt_file to the path of the file that records breakpoint information.
:part_size => 100 * 1024, :cpt_file => '/tmp/example.zip.cpt') { |p|
puts "Progress: #{p}"
}Rubriques connexes
Pour télécharger un objet depuis un bucket dont le contrôle de version est activé, consultez la rubrique Gérer des objets dans un bucket avec contrôle de version activé.
Si vous souhaitez autoriser des utilisateurs tiers à télécharger des objets depuis votre bucket privé (ACL privée), générez des identifiants d'accès temporaires via STS ou utilisez une URL signée. Pour plus d'informations, consultez la rubrique Autoriser des utilisateurs tiers à télécharger des objets.