Todos os produtos
Search
Central de documentação

Object Storage Service:Simple upload (Python SDK V1)

Última atualização: Sep 22, 2026

Use o método put_object para fazer upload de um único objeto para o OSS. Os tipos de entrada compatíveis incluem strings, bytes, caracteres Unicode, fluxos de rede e arquivos locais.

Notas de uso

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

  • Este tópico demonstra a criação de uma instância de OSSClient com um endpoint do OSS. Para outras configurações, como o uso de domínios personalizados ou autenticação via credenciais do Security Token Service (STS), consulte Initialization.

  • Caso um objeto com o mesmo nome já exista no bucket e você tenha as permissões necessárias, o upload sobrescreverá o objeto existente.

Permissões

Por padrão, uma conta da Alibaba Cloud possui permissões completas. Usuários RAM ou funções RAM vinculados a uma conta da Alibaba Cloud não possuem permissões por padrão. O proprietário da conta da Alibaba Cloud ou o administrador deve conceder as permissões de operação por meio de RAM policies ou Bucket Policy.

Parâmetros comuns

A tabela a seguir descreve os parâmetros comuns para o upload de objetos.

Parâmetro

Descrição

bucket_name

O nome do bucket.

O nome do bucket deve seguir estas regras:

  • Conter apenas letras minúsculas, dígitos e hífens (-).

  • Começar e terminar com uma letra minúscula ou um dígito.

  • Ter entre 3 e 63 caracteres.

object_name

O caminho completo do objeto. O caminho completo não pode incluir o nome do bucket.

O nome do objeto deve seguir estas regras:

  • Ser codificado em UTF-8.

  • Ter entre 1 e 1023 caracteres.

  • Não pode começar com uma barra (/) ou uma barra invertida (\).

Upload de uma string

Envie uma string para o objeto exampleobject.txt no bucket examplebucket:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"

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

# Upload the file.
# To set the storage class (x-oss-storage-class) and access permissions (x-oss-object-acl) when uploading the file, set the relevant headers in put_object.
# headers = dict()
# headers["x-oss-storage-class"] = "Standard"
# headers["x-oss-object-acl"] = oss2.OBJECT_ACL_PRIVATE
# Specify the full path of the object and the string. The full path cannot include the bucket name.
# result = bucket.put_object('exampleobject.txt', 'Hello OSS', headers=headers)
result = bucket.put_object('exampleobject.txt', 'Hello OSS')

# HTTP status code.
print('http status: {0}'.format(result.status))
# Request ID. The request ID uniquely identifies this request. Add this parameter to your program logs for easier troubleshooting.
print('request_id: {0}'.format(result.request_id))
# The ETag is a property specific to the return value of the put_object method. It identifies the content of an object.
print('ETag: {0}'.format(result.etag))
# HTTP response header.
print('date: {0}'.format(result.headers['date']))

Upload de bytes

Envie bytes para o objeto exampleobject.txt no bucket examplebucket:

# -*- coding: utf-8 -*-

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"

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

# Specify the full path of the object and the byte content. The full path cannot include the bucket name.
bucket.put_object('exampleobject.txt', b'Hello OSS')

Upload de caracteres Unicode

Envie um caractere Unicode para o objeto exampleobject.txt no bucket examplebucket. O OSS converte automaticamente o caractere Unicode em bytes codificados em UTF-8.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"

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

# Specify the full path of the object and the Unicode character. The full path cannot include the bucket name.
bucket.put_object('exampleobject.txt', u'Hello OSS')

Upload de um fluxo de rede

Envie um fluxo de rede para o objeto exampleobject.txt no bucket examplebucket. O OSS trata o fluxo como um objeto iterável e faz o upload dele com codificação por partes.

# -*- coding: utf-8 -*-
import oss2
import requests
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"

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

# requests.get returns an iterable object. The Python SDK then uploads the object using chunked encoding.
# Specify the network stream URL.
input = requests.get('http://www.aliyun.com')
# Specify the full path of the object. The full path cannot include the bucket name.
bucket.put_object('exampleobject.txt', input)

Upload de um arquivo local

Faça upload do arquivo local examplefile.txt para o bucket examplebucket e salve-o como exampleobject.txt:

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"
# Specify the bucket name, for example, examplebucket.
bucketName = "examplebucket"
# Create a bucket instance and specify the bucket name and region information.
bucket = oss2.Bucket(auth, endpoint, bucketName, region=region)

# The full path of the local file.
local_file_path = 'D:\\localpath\\examplefile.txt'  

# Specify the full path of the object. The full path cannot include the bucket name. For example, exampleobject.txt.
objectName = 'exampleobject.txt'

# Use the put_object_from_file method to upload the local file to OSS.
bucket.put_object_from_file(objectName, local_file_path)

Para enviar a partir de uma posição específica em bytes, utilize o método seek(). O exemplo a seguir inicia o processo a partir do byte 1000:

# -*- coding: utf-8 -*-
import oss2
import os
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the Endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
region = "cn-hangzhou"

# Set yourBucketName to the bucket name, for example, examplebucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Open the file in binary mode and specify the full path of the local file.
with open('D:\\localpath\\examplefile.txt', 'rb') as fileobj:
    # The seek() method specifies to start reading or writing from the 1000th byte. The upload starts from the specified 1000th byte and continues to the end of the file.
    fileobj.seek(1000, os.SEEK_SET)
    # The tell() method returns the current position.
    current = fileobj.tell()
    # Specify the full path of the object. The full path cannot include the bucket name.
    bucket.put_object('exampleobject.txt', fileobj)

Perguntas frequentes

Como obter a URL do arquivo após o upload?

O SDK não retorna a URL do arquivo após o upload. Para obter a URL, consulte Use a signed URL to download or preview a file.

Como verificar se o tamanho do arquivo enviado corresponde ao arquivo local?

  1. O OSS ativa a validação CRC por padrão durante uploads e downloads. Caso o tamanho do arquivo enviado difira do local, o sistema retorna um InconsistentError.

  2. A validação CRC pode reduzir a velocidade de upload. Para priorizar o throughput, desative-a:

    # -*- coding: utf-8 -*-
    import oss2
    import os
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Obtain access credentials from environment variables. Before running the sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the Endpoint for 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.
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
    
    # Specify the region information that corresponds to the Endpoint, for example, cn-hangzhou. Note that this parameter is required for v4 signatures.
    region = "cn-hangzhou"
    
    # Set yourBucketName to the bucket name, and set enable_crc=False to disable CRC data validation. 
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", enable_crc=False, region=region)

Referências