Este tópico descreve como fazer upload rápido de um arquivo local para o Object Storage Service (OSS) por meio do upload simples. Esse método é direto e ideal para cenários que exigem o upload rápido de arquivos locais.
Considerações
O código de exemplo neste tópico usa o ID de região cn-hangzhou (China (Hangzhou)) e o endpoint público por padrão. Caso precise acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use o endpoint interno. Para mais informações sobre o mapeamento entre regiões e endpoints compatíveis com o OSS, consulte OSS regions and endpoints.
Permissões
Por padrão, uma conta Alibaba Cloud tem permissões totais, enquanto usuários RAM ou funções RAM vinculados a ela não possuem nenhuma permissão. A conta Alibaba Cloud ou o administrador deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.
|
API |
Ação |
Descrição |
|
PutObject |
|
Faz upload de um objeto. |
|
|
Necessário ao especificar tags de objeto com o cabeçalho |
|
|
|
Necessário se o cabeçalho |
|
|
|
Upload de arquivos locais
Ao fazer upload de um objeto com o mesmo nome de um objeto existente e acessível, o novo objeto substituirá o anterior.
A tabela a seguir lista os parâmetros comuns a configurar durante o upload de um objeto.
|
Parâmetro |
Descrição |
|
bucket |
O nome do bucket. Os nomes de bucket devem seguir estas convenções:
|
|
key |
O caminho completo do objeto. Não inclua o nome do bucket no caminho. O nome do objeto deve seguir estas convenções de nomenclatura:
|
O código de exemplo a seguir demonstra como fazer upload de um arquivo local para um bucket:
using System.Text; // Import System.Text namespace for handling character encoding (such as UTF-8 encoded strings)
using OSS = AlibabaCloud.OSS.V2; // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent usage
var region = "cn-hangzhou"; // Required, set the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou
var bucket = "your bucket name"; // Required, set the target bucket name
var endpoint = null as string; // Optional, specify the endpoint for accessing OSS service. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com
var key = "your object key"; // Required, specify the object name to upload. Format: (folder/objectName)
var filePath = "/Users/yourLocalPath/yourFileName"; // Required, specify the local file path
// Load the default configuration of OSS SDK, which automatically reads credential information (such as AccessKey) from environment variables
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set to use environment variables for credentials, used for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket region in the configuration
cfg.Region = region;
// If an endpoint is specified, override the default endpoint
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration information
using var client = new OSS.Client(cfg);
// Call PutObjectFromFileAsync method to upload a local file
var result = await client.PutObjectFromFileAsync(new()
{
Bucket = bucket,
Key = key
}, filePath);
// Display the upload result
Console.WriteLine("PutObjectFromFile done"); // Indicate the operation is complete
Console.WriteLine($"StatusCode: {result.StatusCode}"); // HTTP status code
Console.WriteLine($"RequestId: {result.RequestId}"); // RequestId, used for troubleshooting by Alibaba Cloud
Console.WriteLine("Response Headers:"); // Response header information
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Traverse and print all response headers
Upload de arrays de bytes
using System.Text; // Import System.Text namespace for handling character encoding (such as UTF-8 encoded strings)
using OSS = AlibabaCloud.OSS.V2; // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent usage
var region = "cn-hangzhou"; // Required, set the region where the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou
var bucket = "your bucket name"; // Required, set the target bucket name
var endpoint = null as string; // Optional, specify the endpoint for accessing OSS service. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com
var key = "your object key"; // Required, specify the object name to upload. Format: (folder/objectName)
// Load the default configuration of OSS SDK, which automatically reads credential information (such as AccessKey) from environment variables
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set to use environment variables for credentials, used for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the bucket region in the configuration
cfg.Region = region;
// If an endpoint is specified, override the default endpoint
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration information
using var client = new OSS.Client(cfg);
// Content to be uploaded. Example content: simple string "hello oss!", in actual scenarios it could be file streams, byte arrays, etc.
var content = "hello oss!";
// Convert the string to a UTF-8 encoded byte array, then wrap it in a MemoryStream
// MemoryStream is used to process data streams in memory, suitable for small file uploads; for large files, FileStream is recommended
var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
// Call PutObjectAsync method to asynchronously upload an object (requires a request object containing Bucket, Key, and Body)
// This method will upload the data from bodyStream to the specified Key path in the target Bucket
var result = await client.PutObjectAsync(new OSS.Models.PutObjectRequest()
{
Bucket = bucket, // Target bucket name
Key = key, // Unique key of the object in the bucket
Body = bodyStream // Content stream to upload (in this case, string data in memory)
});
// Display the upload result
Console.WriteLine("PutObject done"); // Indicate the operation is complete
Console.WriteLine($"StatusCode: {result.StatusCode}"); // HTTP status code
Console.WriteLine($"RequestId: {result.RequestId}"); // RequestId, used for troubleshooting by Alibaba Cloud
Console.WriteLine("Response Headers:"); // Response header information
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Traverse and print all response headers
Referências
Para o código de exemplo completo de upload simples, consulte putObject.cs.