O upload simples é um método utilizado para enviar um objeto por meio da operação PutObject. Com esse método, você faz o upload de uma string ou de um arquivo local para o Object Storage Service (OSS) no modo síncrono ou assíncrono. Você também pode verificar o MD5 para garantir a integridade dos dados durante o upload simples.
Observações
Neste tópico, utilizamos o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou a autenticação com credenciais do Security Token Service (STS), consulte Initialization (C# SDK V1).
Permissões
Por padrão, uma conta Alibaba Cloud possui permissões totais. Usuários RAM ou funções RAM vinculados a uma conta Alibaba Cloud não possuem permissões por padrão. A conta Alibaba Cloud ou o administrador da conta deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.
|
API |
Ação |
Descrição |
|
PutObject |
|
Faz o upload de um objeto. |
|
|
Necessário caso você especifique tags de objeto por meio do cabeçalho |
|
|
|
Necessário caso o cabeçalho |
|
|
|
Upload de uma string
O código de exemplo a seguir demonstra como fazer o upload de uma string para um objeto chamado exampleobject.txt em um bucket chamado 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);
}
Upload de um arquivo local
O código de exemplo a seguir demonstra como fazer o upload de um arquivo local chamado examplefile.txt para um bucket chamado examplebucket. O arquivo enviado é armazenado no OSS como um objeto chamado exampleobject.txt.
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);
}
Upload de um arquivo local com verificação de MD5
Para garantir que os dados enviados pelo cliente sejam idênticos aos recebidos pelo servidor OSS, adicione o cabeçalho Content-MD5 à requisição como um item de metadados do objeto. O servidor OSS utiliza o valor desse cabeçalho para verificar o MD5.
Atenção: a verificação de MD5 impacta negativamente o desempenho do OSS.
O código de exemplo a seguir demonstra como verificar o MD5 durante o upload de um arquivo 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);
}
Upload de um arquivo local no modo assíncrono
O código de exemplo a seguir demonstra como fazer o upload de um arquivo local chamado examplefile.txt para um bucket chamado examplebucket no modo assíncrono. O arquivo enviado é armazenado no OSS como um objeto chamado exampleobject.txt. Ao fazer o upload de um arquivo local no modo assíncrono, implemente uma função para processar as informações de callback.
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();
}
}
}