Todos os produtos
Search
Central de documentação

Object Storage Service:Upload simples (Python SDK V2)

Última atualização: Jul 03, 2026

Faça upload de um único arquivo para o OSS usando o método de upload simples no Python SDK V2.

Observações de uso

O código de exemplo deste tópico usa o ID da região China (Hangzhou) cn-hangzhou e um endpoint público. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para ver os mapeamentos entre regiões e endpoints, consulte Regiões e endpoints do OSS.

Permissões

Por padrão, uma conta Alibaba Cloud tem permissões totais. Usuários RAM ou funções RAM vinculados a essa conta não possuem permissões iniciais. A conta Alibaba Cloud ou o administrador deve conceder as permissões de operação por meio de políticas do RAM ou Bucket Policy.

API

Action

Description

PutObject

oss:PutObject

Faz upload de um objeto.

oss:PutObjectTagging

Necessário se você especificar tags de objeto com o cabeçalho x-oss-tagging durante o upload.

kms:GenerateDataKey

Necessário se o cabeçalho X-Oss-Server-Side-Encryption: KMS estiver definido como KMS durante o upload.

kms:Decrypt

Definição do método

put_object(request: PutObjectRequest, **kwargs) → PutObjectResult

Parâmetros da solicitação

Parâmetro

Tipo

Descrição

request

PutObjectRequest

Os parâmetros da solicitação, incluindo a ACL do objeto, a opção de proibir substituição (ForbidOverwrite) e metadados personalizados (Metadata). PutObjectRequest

Valores de retorno

Tipo

Descrição

PutObjectResult

O valor de retorno. PutObjectResult

Para obter a definição completa do método, consulte put_object.

Upload de um arquivo local

Se já existir um objeto com o mesmo nome no bucket e você tiver as permissões necessárias, o novo objeto substituirá o existente.

Parâmetros comuns:

Parameter

Description

bucket_name

Nome do bucket.

Convenções de nomenclatura de bucket:

  • Contém apenas letras minúsculas, dígitos e hifens (-).

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

  • Deve ter entre 3 e 63 caracteres.

object_name

Caminho completo do objeto, excluindo o nome do bucket.

Convenções de nomenclatura de objeto:

  • Deve estar codificado em UTF-8.

  • Deve ter entre 1 e 1.023 caracteres.

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

Use put_object_from_file para fazer upload de um arquivo local para o bucket de destino.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object from file sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

# Add the --file_path command-line argument, which specifies the path of the local file to upload. This argument is required.
parser.add_argument('--file_path', help='The path of Upload file.', required=True)

def main():
    # Parse the command-line arguments.
    args = parser.parse_args()

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the software development kit (SDK) and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region in the configuration.
    cfg.region = args.region

    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the specified configurations.
    client = oss.Client(cfg)

    # Execute the request to upload the object directly from a file.
    # Specify the bucket name, object name, and local file path.
    result = client.put_object_from_file(
        oss.PutObjectRequest(
            bucket=args.bucket,  # The name of the bucket.
            key=args.key         # The name of the object.
        ),
        args.file_path          # The path of the local file.
    )

    # Print the result information of the request, including the status code, request ID, Content-MD5, ETag, 64-bit cyclic redundancy check (CRC64) hash, version ID, and server response time.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
          f' server time: {result.headers.get("x-oss-server-time")},'
    )

# The script entry point. The main function is called when the file is run directly.
if __name__ == "__main__":
    main()

Ao usar put_object para fazer upload de um arquivo local, abra-o no modo 'rb'. Isso garante o envio do fluxo de bytes original em vez do conteúdo de texto, evitando falhas de CRC.

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object from file sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)

# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)

# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line arguments.
    args = parser.parse_args()

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region in the configuration.
    cfg.region = args.region

    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the specified configurations.
    client = oss.Client(cfg)

    # Execute the request to upload the object directly from a local file.
    # Specify the bucket name, object name, and local file path.
    with open('your-test-file.md', 'rb') as f:
    result = client.put_object(
        oss.PutObjectRequest(
            bucket=args.bucket,  # The name of the bucket.
            key=args.key,        # The name of the object.
            body=f.read()        # Read the file content.
        )
    )

    # Print the result information of the request, including the status code, request ID, Content-MD5, ETag, CRC64 hash, version ID, and server response time.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
          f' server time: {result.headers.get("x-oss-server-time")},'
    )

# The script entry point. The main function is called when the file is run directly.
if __name__ == "__main__":
    main()

Exemplos

Upload a string

Faça upload de uma string para o bucket de destino:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command-line arguments.

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    cfg.region = args.region
    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the specified configurations.
    client = oss.Client(cfg)

    # Define the string to upload.
    text_string = "Hello, OSS!"
    data = text_string.encode('utf-8')  # Encode the string into a UTF-8 byte string.

    # Execute the request to upload the object. Specify the bucket name, object name, and data content.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
    ))

    # Print the status code, request ID, Content-MD5, ETag, CRC64 hash, and version ID of the request result to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # The script entry point. The main function is called when the file is run directly.

Upload a byte array

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command-line arguments.

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    cfg.region = args.region
    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the specified configurations.
    client = oss.Client(cfg)

    # Define the data content to upload.
    data = b'hello world'

    # Execute the request to upload the object. Specify the bucket name, object name, and data content.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
    ))

    # Print the status code, request ID, Content-MD5, ETag, CRC64 hash, and version ID of the request result to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # The script entry point. The main function is called when the file is run directly.

Upload a network stream

Faça upload de um fluxo de rede para o bucket de destino:

import argparse
import requests
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command-line arguments.

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    cfg.region = args.region
    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the specified configurations.
    client = oss.Client(cfg)

    # Send an HTTP GET request to obtain the response content.
    response = requests.get('http://www.aliyun.com')

    # Execute the request to upload the object. Specify the bucket name, object name, and data content.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=response.content,
    ))

    # Print the status code, request ID, Content-MD5, ETag, CRC64 hash, and version ID of the request result to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # The script entry point. The main function is called when the file is run directly.

Upload with callback

Notifique um servidor de aplicativos após o upload de um arquivo:

import base64
import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put object sample")

# Add the required parameters.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--call_back_url', help='Callback server address.', required=True)

def main():

    args = parser.parse_args()

    # Load credentials from environment variables.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Configure the SDK client.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client.
    client = oss.Client(cfg)

    # The content to upload (a string).
    data = 'hello world'

    # Construct the callback parameter (callback): Specify the webhook address and the callback request body, and use Base64 encoding.
    callback=base64.b64encode(str('{\"callbackUrl\":\"' + args.call_back_url + '\",\"callbackBody\":\"bucket=${bucket}&object=${object}&my_var_1=${x:var1}&my_var_2=${x:var2}\"}').encode()).decode()
    # Construct the custom variable (callback-var) and use Base64 encoding.
    callback_var=base64.b64encode('{\"x:var1\":\"value1\",\"x:var2\":\"value2\"}'.encode()).decode()

    # Initiate an upload request that includes the callback parameters.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
        callback=callback,
        callback_var=callback_var,
    ))
    # Print the returned result, including the status code and request ID.
    print(vars(result))

if __name__ == "__main__":
    main()

Upload with progress bar

Exiba o progresso de upload de um arquivo local com uma barra de progresso:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command-line arguments.

    # Load credentials from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and set the credentials provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Set the region in the configuration.
    cfg.region = args.region
    # If the endpoint argument is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create an OSS client using the specified configurations.
    client = oss.Client(cfg)

    # Define a dictionary variable named progress_state to save the upload progress status. The initial value is 0.
    progress_state = {'saved': 0}
    def _progress_fn(n, written, total):
        # Use a dictionary to store the cumulative number of written bytes to avoid using global variables.
        progress_state['saved'] += n

        # Calculate the current upload percentage. Divide the number of written bytes by the total number of bytes and round down the result.
        rate = int(100 * (float(written) / float(total)))

        # Print the current upload progress. \r indicates returning to the beginning of the line to implement real-time refresh in the command line.
        # end='' indicates that no line break is added, so that the next printout overwrites the current line.
        print(f'\rUpload progress: {rate}% ', end='')

    # Execute the request to upload the object. Specify the bucket name, object name, and data content.
    result = client.put_object_from_file(oss.PutObjectRequest(
            bucket=args.bucket,
            key=args.key,
            progress_fn=_progress_fn,
        ),
        "/local/dir/example", # Specify the path of the local file.
    )

    # Print the status code, request ID, Content-MD5, ETag, CRC64 hash, and version ID of the request result to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # The script entry point. The main function is called when the file is run directly.

Referências

  • Para obter o código de exemplo completo, consulte put_object.py.