Cette rubrique explique comment télécharger des fichiers (objets) vers un bucket pour lequel la gestion des versions est activée.
Notes
Cette rubrique utilise l'endpoint public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour plus d'informations sur les régions et les endpoints OSS, consultez Régions et endpoints.
Cette rubrique montre comment créer une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, comme l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation (C# SDK V1).
Pour télécharger un objet, vous devez disposer de l'autorisation
oss:PutObject. Pour plus d'informations, consultez Accorder une politique personnalisée.
Téléchargement simple
Lorsque vous envoyez une requête de téléchargement d'un objet vers un bucket avec gestion des versions activée, OSS génère un ID de version unique pour l'objet téléchargé et inclut cet ID dans la réponse en tant que valeur de l'en-tête x-oss-version-id. Si vous téléchargez un objet vers un bucket dont la gestion des versions est suspendue, OSS attribue à l'objet un ID de version null. Si l'objet que vous téléchargez porte le même nom qu'un objet existant, ce dernier est écrasé par l'objet téléchargé. Ainsi, chaque objet ne possède qu'une seule version, dont l'ID de version est null.
Le code suivant montre comment effectuer un téléchargement simple :
using System.Text;
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 this 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");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
var objectContent = "More than just cloud.";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
// Upload the object.
var result = client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded versionid : {0}", result.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
Téléchargement par ajout
Dans un bucket avec gestion des versions activée, l'opération AppendObject ne peut s'effectuer que sur la version actuelle d'un objet pouvant faire l'objet d'ajouts.
Lorsque vous exécutez l'opération AppendObject sur la version actuelle d'un objet pouvant faire l'objet d'ajouts, OSS ne génère pas de version précédente pour cet objet.
Lorsque vous exécutez l'opération PutObject ou DeleteObject sur un objet dont la version actuelle est un objet pouvant faire l'objet d'ajouts, OSS conserve l'objet en tant que version précédente et empêche tout ajout ultérieur à cet objet.
L'opération AppendObject ne peut pas s'exécuter sur un objet dont la version actuelle n'est pas un objet pouvant faire l'objet d'ajouts, comme un objet normal ou un marqueur de suppression.
Le code suivant montre comment effectuer un téléchargement par ajout :
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 this 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");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
// Set localFilename to the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the project directory of the sample program.
var localFilename = "D:\\localpath\\examplefile.txt";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// The position for the first append operation is 0. The response contains the position for the next append operation. The position for subsequent append operations is the length of the object before the append.
long position = 0;
try
{
var metadata = client.GetObjectMetadata(bucketName, objectName);
position = metadata.ContentLength;
}
catch (Exception) { }
try
{
using (var fs = File.Open(localFilename, FileMode.Open))
{
var request = new AppendObjectRequest(bucketName, objectName)
{
ObjectMetadata = new ObjectMetadata(),
Content = fs,
Position = position
};
// Append data to the object.
var result = client.AppendObject(request);
// Set the position for the append operation.
position = result.NextAppendPosition;
Console.WriteLine("Append object succeeded, next append position:{0}, vesionid:{1}", position, result.VersionId);
}
// Get the append position and append data to the object again.
using (var fs = File.Open(localFilename, FileMode.Open))
{
var request = new AppendObjectRequest(bucketName, objectName)
{
ObjectMetadata = new ObjectMetadata(),
Content = fs,
Position = position
};
var result = client.AppendObject(request);
position = result.NextAppendPosition;
Console.WriteLine("Append object succeeded, next append position:{0}, vesionid:{1}", position, result.VersionId);
}
}
catch (Exception ex)
{
Console.WriteLine("Append object failed, {0}", ex.Message);
}
Téléchargement en plusieurs parties
Si vous appelez l'opération CompleteMultipartUpload pour finaliser la tâche de téléchargement en plusieurs parties d'un objet dans un bucket avec gestion des versions activée, OSS génère un ID de version unique pour l'objet et renvoie cet ID en tant que valeur de l'en-tête x-oss-version-id dans la réponse.
Le code suivant montre comment effectuer un téléchargement en plusieurs parties :
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 this 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");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Set localFilename to the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the project directory of the sample program.
var localFilename = "D:\\localpath\\examplefile.txt";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Initialize the multipart upload.
var uploadId = "";
try
{
// Specify the name of the object to upload and the bucket where it is stored. In InitiateMultipartUploadRequest, you can set ObjectMeta, but you do not need to specify ContentLength.
var request = new InitiateMultipartUploadRequest(bucketName, objectName);
var result = client.InitiateMultipartUpload(request);
uploadId = result.UploadId;
// Print the UploadId.
Console.WriteLine("Init multi part upload succeeded");
Console.WriteLine("Upload Id:{0}", result.UploadId);
}
catch (Exception ex)
{
Console.WriteLine("Init multi part upload failed, {0}", ex.Message);
}
// Calculate the total number of parts.
var partSize = 100 * 1024;
var fi = new FileInfo(localFilename);
var fileSize = fi.Length;
var partCount = fileSize / partSize;
if (fileSize % partSize != 0)
{
partCount++;
}
// Start the multipart upload. partETags is a list that stores the ETag of each part. After OSS receives the part list, it verifies each part. After all parts are verified, OSS combines them into a complete object.
var partETags = new List<PartETag>();
try
{
using (var fs = File.Open(localFilename, FileMode.Open))
{
for (var i = 0; i < partCount; i++)
{
var skipBytes = (long)partSize * i;
// Go to the start position for the current upload.
fs.Seek(skipBytes, 0);
// Calculate the size of the part to upload. The size of the last part is the remaining data size.
var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
var request = new UploadPartRequest(bucketName, objectName, uploadId)
{
InputStream = fs,
PartSize = size,
PartNumber = i + 1
};
// Call the UploadPart operation to upload the part. The response contains the ETag of the part.
var result = client.UploadPart(request);
partETags.Add(result.PartETag);
Console.WriteLine("finish {0}/{1}", partETags.Count, partCount);
}
Console.WriteLine("Put multi part upload succeeded");
}
}
catch (Exception ex)
{
Console.WriteLine("Put multi part upload failed, {0}", ex.Message);
}
// Complete the multipart upload.
try
{
var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
foreach (var partETag in partETags)
{
completeMultipartUploadRequest.PartETags.Add(partETag);
}
var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
Console.WriteLine("CompleteMultipartUpload succeeded, vesionid:{0}", result.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("complete multi part failed, {0}", ex.Message);
}
Références
Pour plus d'informations sur le téléchargement simple, consultez PutObject.
Pour plus d'informations sur le téléchargement par ajout, consultez AppendObject.
Pour plus d'informations sur le téléchargement en plusieurs parties, consultez CompleteMultipartUpload.