Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement simple (OSS SDK pour C# 1.0)

Dernière mise à jour :Aug 18, 2026

Le téléchargement simple permet de charger un objet via l'opération PutObject. Vous pouvez utiliser cette méthode pour envoyer une chaîne ou un fichier local vers Object Storage Service (OSS) en mode synchrone ou asynchrone. Vous pouvez également vérifier l'intégrité des données par MD5 lors du téléchargement simple.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Cette rubrique explique comment créer une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation (SDK C# V1).

Permissions

Par défaut, un compte Alibaba Cloud dispose de toutes les permissions. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune permission par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les permissions d'opération via des politiques RAM ou une Bucket Policy.

API

Action

Description

PutObject

oss:PutObject

Charge un objet.

oss:PutObjectTagging

Requis si vous spécifiez des tags d'objet à l'aide de l'en-tête x-oss-tagging lors du chargement d'un objet.

kms:GenerateDataKey

Requis si l'en-tête X-Oss-Server-Side-Encryption: KMS est défini sur KMS lors du chargement d'un objet.

kms:Decrypt

Charger une chaîne

L'exemple de code suivant montre comment charger une chaîne dans un objet nommé exampleobject.txt d'un bucket nommé examplebucket :

using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the string that you want to upload. 
var objectContent = "More than just cloud.";
// 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.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
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. 
    client.PutObject(bucketName, objectName, requestContent);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}

Charger un fichier local

L'exemple de code suivant montre comment charger un fichier local nommé examplefile.txt dans un bucket nommé examplebucket. Le fichier chargé est stocké sous forme d'objet nommé exampleobject.txt dans OSS.

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
var localFilename = "D:\\localpath\\examplefile.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.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Upload the local file. 
    client.PutObject(bucketName, objectName, localFilename);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}

Charger un fichier local et vérifier le MD5

Pour garantir que les données envoyées par le client sont identiques à celles reçues par le serveur OSS, ajoutez l'en-tête Content-MD5 à la requête en tant que métadonnée de l'objet. Le serveur OSS utilise la valeur de cet en-tête pour vérifier le MD5.

Important

La vérification MD5 affecte négativement les performances d'OSS.

L'exemple de code suivant montre comment vérifier le MD5 lors du chargement d'un fichier local :

using System;
using System.IO;

using Aliyun.OSS;
using Aliyun.OSS.Util;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
var localFilename = "D:\\localpath\\examplefile.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.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Calculate the MD5 hash. 
    string md5;
    using (var fs = File.Open(localFilename, FileMode.Open))
    {
        md5 = OssUtils.ComputeContentMd5(fs, fs.Length);
    }
    var objectMeta = new ObjectMetadata
    {
        ContentMd5 = md5
    };
    // Upload the local file. 
    client.PutObject(bucketName, objectName, localFilename, objectMeta);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}

Charger un fichier local en mode asynchrone

L'exemple de code suivant montre comment charger un fichier local nommé examplefile.txt dans un bucket nommé examplebucket en mode asynchrone. Le fichier chargé est stocké sous forme d'objet nommé exampleobject.txt dans OSS. Lors du chargement asynchrone d'un fichier local, vous devez implémenter une fonction pour traiter les informations de rappel.

using System;
using System.IO;
using System.Threading;

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Upload a local file in asynchronous mode. 
namespace AsyncPutObject
{
    class Program
    {
        // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        static string 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 configured. 
        var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
        var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
        // Specify the name of the bucket. Example: examplebucket. 
        static string bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        static string objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
        static string localFilename = "D:\\localpath\\examplefile.txt";

        static AutoResetEvent _event = new AutoResetEvent(false);
        // 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.
        const string region = "cn-hangzhou";
        // Create a ClientConfiguration instance and modify the default parameters based on your requirements.
        var conf = new ClientConfiguration();
        // Use the signature algorithm V4.
        conf.SignatureVersion = SignatureVersion.V4;
        
        // Create an OSSClient instance.
        var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
        client.SetRegion(region);
        
        private static void PutObjectCallback(IAsyncResult ar)
        {
            try
            {
                client.EndPutObject(ar);
                Console.WriteLine(ar.AsyncState as string);
                Console.WriteLine("Put object succeeded");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                _event.Set();
            }
        }

        public static void AsyncPutObject()
        {
            try
            {
                using (var fs = File.Open(localFilename, FileMode.Open))
                {
                    var metadata = new ObjectMetadata();
                    // Add user metadata. 
                    metadata.UserMetadata.Add("mykey1", "myval1");
                    metadata.UserMetadata.Add("mykey2", "myval2");
                    metadata.CacheControl = "No-Cache";
                    metadata.ContentType = "text/txt";
                    string result = "Notice user: put object finish";

                    // Upload the local file in asynchronous mode. 
                    client.BeginPutObject(bucketName, objectName, fs, metadata, PutObjectCallback, result.ToCharArray());

                    _event.WaitOne();
                }
            }
            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);
            }
        }

        static void Main(string[] args)
        {
            Program.AsyncPutObject();
        }
    }
}            

Références

  • Pour obtenir l'exemple de code complet utilisé pour effectuer un téléchargement simple, visitez GitHub.

  • Pour plus d'informations sur l'opération API que vous pouvez appeler pour effectuer un téléchargement simple, consultez PutObject.