Todos os produtos
Search
Central de documentação

Object Storage Service:Upload objects (OSS SDK for Python 1.0)

Última atualização: Sep 22, 2026

Este tópico descreve como enviar objetos para um bucket com versionamento usando upload simples, upload por anexação e upload em várias partes.

Observações

  • Este tópico usa 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 do OSS, utilize um endpoint interno. Para obter mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Neste tópico, obtemos as credenciais de acesso a partir de variáveis de ambiente. Para obter mais informações sobre como configurar as credenciais de acesso, consulte Configure access credentials using OSS SDK for Python 1.0.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Initialization.

  • Para enviar um objeto, você deve ter a permissão oss:PutObject. Para obter mais informações, consulte Grant a custom policy.

Upload simples

Ao iniciar uma solicitação para enviar um objeto para um bucket com versionamento ativado, o OSS gera um ID de versão exclusivo para o objeto. Além disso, inclui esse ID na resposta como o valor do cabeçalho x-oss-version-id. Se você enviar um objeto para um bucket com versionamento suspenso, o OSS gera um ID de versão nulo para o objeto. Caso o objeto enviado tenha o mesmo nome de um objeto existente, o objeto enviado substituirá o existente. Dessa forma, cada objeto tem apenas uma versão cujo ID de versão é nulo.

O código de exemplo a seguir demonstra como usar o upload simples para enviar um objeto a um bucket com versionamento ativado:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Upload the object. 
result = bucket.put_object('yourObjectName', 'content of object')
# Display the returned HTTP status code. 
print('http response code: {0}'.format(result.status))
# Display the version ID of the uploaded object. 
print('put object version:', result.versionid)

Upload por anexação

Em um bucket com versionamento ativado, execute a operação AppendObject apenas na versão atual de um objeto anexável.

Nota
  • Ao executar a operação AppendObject na versão atual de um objeto anexável, o OSS não gera uma versão anterior para o objeto.

  • Ao executar a operação PutObject ou DeleteObject em um objeto cuja versão atual é um objeto anexável, o OSS armazena o objeto anexável como uma versão anterior e impede novos acréscimos ao objeto.

  • Você não pode executar a operação AppendObject em um objeto cuja versão atual não seja anexável, como um objeto normal ou um marcador de exclusão.

O código de exemplo a seguir demonstra como enviar um objeto utilizando o upload por anexação:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Set the position from which the first append operation starts to 0. 
result = bucket.append_object('yourObjectName', 0, 'content of first append')
# Display the version ID of the object that is appended. 
print('append object versionid:', result.versionid)
# If you have appended content to the object, you can obtain the position from which the operation starts this time from the next_position field in the response returned by the last operation or by using the bucket.head_object method. 
bucket.append_object('yourObjectName', result.next_position, 'content of second append')

Upload em várias partes

Ao chamar a operação CompleteMultipartUpload para concluir a tarefa de upload em várias partes de um objeto em um bucket com versionamento ativado, o OSS gera um ID de versão exclusivo para o objeto e retorna esse ID como o valor do cabeçalho x-oss-version-id na resposta.

O código de exemplo a seguir demonstra como enviar um objeto para um bucket com versionamento ativado usando o upload em várias partes:

# -*- coding: utf-8 -*-
import os
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2 import SizedFileAdapter, determine_part_size
from oss2.models import PartInfo
# 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. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

key = 'yourObjectName'
filename = 'yourLocalFile'

total_size = os.path.getsize(filename)
# Specify the determine_part_size method to determine the part size. 
part_size = determine_part_size(total_size, preferred_size=100 * 1024)

# Initiate a multipart upload task. 
upload_id = bucket.init_multipart_upload(key).upload_id
parts = []

# Upload the parts. 
with open(filename, 'rb') as fileobj:
    part_number = 1
    offset = 0
    while offset < total_size:
        num_to_upload = min(part_size, total_size - offset)
    # The SizedFileAdapter(fileobj, size) method generates a new object and recalculates the position from which the append operation starts. 
        result = bucket.upload_part(key, upload_id, part_number,
                                    SizedFileAdapter(fileobj, num_to_upload))
        parts.append(PartInfo(part_number, result.etag))

        offset += num_to_upload
        part_number += 1

# Complete the multipart upload task. 
result = bucket.complete_multipart_upload(key, upload_id, parts)
# Display the version ID of the uploaded object, which is returned in the response.
print('result.versionid:', result.versionid)

# Verify the result of the multipart upload task. 
with open(filename, 'rb') as fileobj:
    assert bucket.get_object(key).read() == fileobj.read()

Referências

  • Para obter mais informações sobre a operação de API para upload simples, consulte PutObject.

  • Para mais detalhes sobre a operação de API para upload por anexação, consulte AppendObject.

  • Para saber mais sobre a operação de API para concluir um upload em várias partes, consulte CompleteMultipartUpload.