All Products
Search
Document Center

Object Storage Service:Simple upload (OSS SDK for Python 2.0)

Last Updated:Mar 17, 2026

Upload an object up to 5 GB to OSS in a single HTTP request using the alibabacloud_oss_v2 SDK. For objects larger than 5 GB, use multipart upload.

Quick start

Copy this script to verify your setup. Replace the placeholder values with your bucket name, object key, and file path.

import alibabacloud_oss_v2 as oss

credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = 'cn-hangzhou'  # Replace with your bucket's region
client = oss.Client(cfg)

result = client.put_object_from_file(
    oss.PutObjectRequest(
        bucket='examplebucket',
        key='exampledir/exampleobject.txt',
    ),
    '/path/to/local/file.txt',
)

print(f'ETag: {result.etag}, Request ID: {result.request_id}')

For the full list of region IDs, see OSS regions and endpoints. For additional sample code, see put_object.py.

Prerequisites

Before you begin, ensure that you have:

  • alibabacloud_oss_v2 installed:

      pip install alibabacloud-oss-v2
  • An OSS bucket that meets the bucket naming conventions

  • oss:PutObject permission granted through a RAM policy or bucket policy

  • Your AccessKey ID and AccessKey secret stored as environment variables (ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET)

Alibaba Cloud accounts have full permissions by default. RAM users and RAM roles have no permissions by default and must be explicitly granted oss:PutObject access. Additional permissions are required for specific features: oss:PutObjectTagging for object tagging, and kms:GenerateDataKey and kms:Decrypt for KMS encryption.

Choose a method

Both put_object_from_file and put_object accept a PutObjectRequest and return a PutObjectResult. Choose based on your data source:

MethodBest forInputAdvantage
put_object_from_fileLocal filesFile path (string)Reads in binary mode and handles CRC-64 verification automatically
put_objectStrings, byte arrays, streams, or any in-memory databytes or file-like objectWorks with any data source

For the complete API reference, see put_object.

Important

If an object with the same name already exists in the bucket, the upload overwrites it without warning. To prevent accidental overwrites, set forbid_overwrite=True in PutObjectRequest.

Set up the client

All examples on this page use the following client setup. Create the client once and reuse it across upload operations.

Set your AccessKey credentials as environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Initialize the client:

import alibabacloud_oss_v2 as oss

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

# Load the default SDK configuration
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = 'cn-hangzhou'  # Replace with your bucket's region

# Optional: specify a custom endpoint
# cfg.endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

client = oss.Client(cfg)

Replace cn-hangzhou with the region where your bucket is located. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For a full list of region IDs and endpoints, see OSS regions and endpoints.

Upload a local file

Use put_object_from_file to upload a file from a local path. The method reads the file in binary mode and handles CRC-64 verification automatically.

def upload_file(bucket_name, object_key, file_path):
    """Upload a local file to OSS.

    Args:
        bucket_name: Name of the target bucket.
        object_key:  Object key (full path in OSS, excluding the bucket name).
        file_path:   Absolute or relative path to the local file.

    Returns:
        PutObjectResult on success, None on failure.
    """
    try:
        result = client.put_object_from_file(
            oss.PutObjectRequest(
                bucket=bucket_name,
                key=object_key,
                forbid_overwrite=True,        # Prevent accidental overwrites
            ),
            file_path,
        )
        print(f'Upload succeeded.'
              f' Status code: {result.status_code},'
              f' Request ID: {result.request_id},'
              f' ETag: {result.etag}')
        return result
    except oss.exceptions.OperationError as e:
        print(f'Upload failed: {e}')
        return None

Alternatively, open the file in binary mode and pass its content to put_object. Use binary mode ('rb') to avoid CRC-64 verification failures:

with open('/path/to/local/file.txt', 'rb') as f:
    result = client.put_object(
        oss.PutObjectRequest(
            bucket='examplebucket',
            key='exampledir/exampleobject.txt',
            body=f.read(),
        )
    )

print(f'Status code: {result.status_code},'
      f' Request ID: {result.request_id},'
      f' ETag: {result.etag}')

Upload in-memory data

Use put_object when your data is already in memory.

Upload a string

Encode the string to bytes before passing it as the request body:

data = 'Hello, OSS!'.encode('utf-8')

result = client.put_object(oss.PutObjectRequest(
    bucket='examplebucket',
    key='exampledir/exampleobject.txt',
    body=data,
))

print(f'Status code: {result.status_code},'
      f' Request ID: {result.request_id},'
      f' ETag: {result.etag}')

Upload a byte array

Pass a bytes literal as the request body:

data = b'hello world'

result = client.put_object(oss.PutObjectRequest(
    bucket='examplebucket',
    key='exampledir/exampleobject.txt',
    body=data,
))

print(f'Status code: {result.status_code},'
      f' Request ID: {result.request_id},'
      f' ETag: {result.etag}')

Upload a network stream

Fetch content from a URL and upload the response body:

import requests

response = requests.get('http://www.aliyun.com')

result = client.put_object(oss.PutObjectRequest(
    bucket='examplebucket',
    key='exampledir/exampleobject.txt',
    body=response.content,
))

print(f'Status code: {result.status_code},'
      f' Request ID: {result.request_id},'
      f' ETag: {result.etag}')

Upload with a callback

OSS can notify an application server after an upload completes. Base64-encode the upload callback configuration and any custom variables, then pass them in the request:

import base64

# Upload callback configuration (Base64-encoded JSON)
callback = base64.b64encode(
    ('{"callbackUrl":"<your-callback-url>",'
     '"callbackBody":"bucket=${bucket}&object=${object}'
     '&my_var_1=${x:var1}&my_var_2=${x:var2}"}').encode()
).decode()

# Custom variables (Base64-encoded JSON)
callback_var = base64.b64encode(
    '{"x:var1":"value1","x:var2":"value2"}'.encode()
).decode()

result = client.put_object(oss.PutObjectRequest(
    bucket='examplebucket',
    key='exampledir/exampleobject.txt',
    body=b'hello world',
    callback=callback,
    callback_var=callback_var,
))

print(vars(result))

Replace <your-callback-url> with the URL of your callback server.

Track upload progress

Pass a progress_fn callback to monitor upload progress. The following example uses threading.Lock() to make the progress handler safe for concurrent uploads:

import os
import sys
import threading

class UploadProgress:
    """Thread-safe upload progress tracker."""

    def __init__(self, filename):
        self._filename = filename
        self._written = 0
        self._lock = threading.Lock()

    def __call__(self, n, written, total):
        with self._lock:
            self._written = written
            rate = int(100 * (written / total))
            sys.stdout.write(f'\rUpload progress: {rate}% ')
            sys.stdout.flush()

tracker = UploadProgress('/path/to/local/file.txt')

result = client.put_object_from_file(
    oss.PutObjectRequest(
        bucket='examplebucket',
        key='exampledir/exampleobject.txt',
        progress_fn=tracker,
    ),
    '/path/to/local/file.txt',
)

print(f'\nStatus code: {result.status_code},'
      f' Request ID: {result.request_id},'
      f' ETag: {result.etag}')

The progress_fn callable receives three arguments:

ParameterDescription
nBytes transferred in this chunk
writtenTotal bytes transferred so far
totalTotal file size in bytes

Common configurations

The following snippets show how to set frequently used options in PutObjectRequest. Combine these parameters with any upload method.

Set the MIME type

Set content_type to control how clients interpret the uploaded object:

result = client.put_object_from_file(
    oss.PutObjectRequest(
        bucket='examplebucket',
        key='exampledir/photo.jpg',
        content_type='image/jpeg',
    ),
    '/path/to/photo.jpg',
)

Add object tags

Tags use URL query-string format (key=value pairs separated by &). Object tagging requires the oss:PutObjectTagging permission:

result = client.put_object_from_file(
    oss.PutObjectRequest(
        bucket='examplebucket',
        key='exampledir/exampleobject.txt',
        tagging='env=prod&team=backend',
    ),
    '/path/to/local/file.txt',
)

Enable server-side encryption

Set server_side_encryption to encrypt objects at rest. Valid values are AES256, KMS, and SM4. To use KMS, also grant kms:GenerateDataKey and kms:Decrypt:

result = client.put_object_from_file(
    oss.PutObjectRequest(
        bucket='examplebucket',
        key='exampledir/exampleobject.txt',
        server_side_encryption='AES256',
    ),
    '/path/to/local/file.txt',
)

Combine multiple options

Set multiple parameters in a single request. This example uploads a file with a MIME type, object tags, encryption, and overwrite protection:

result = client.put_object_from_file(
    oss.PutObjectRequest(
        bucket='examplebucket',
        key='exampledir/report.pdf',
        content_type='application/pdf',
        tagging='dept=finance&year=2026',
        server_side_encryption='AES256',
        forbid_overwrite=True,
    ),
    '/path/to/report.pdf',
)

PutObjectRequest parameters

ParameterTypeDescription
bucketstrBucket name (required)
keystrObject key — the full path excluding the bucket name (required)
bodybytes or file-likeObject content
forbid_overwriteboolPrevent overwriting an existing object with the same name
aclstrAccess control list (ACL) for the object. Valid values: private, public-read, public-read-write
storage_classstrStorage class. Valid values: Standard, IA (Infrequent Access), Archive, ColdArchive, DeepColdArchive
content_typestrMIME type of the object (for example, text/plain, image/jpeg)
callbackstrBase64-encoded upload callback configuration
callback_varstrBase64-encoded custom upload callback variables
progress_fncallableProgress callback for tracking upload progress
taggingstrObject tags in URL query-string format (for example, key1=value1&key2=value2)
server_side_encryptionstrServer-side encryption method. Valid values: AES256, KMS, SM4

PutObjectResult fields

Both upload methods return a PutObjectResult with the following fields:

FieldDescription
status_codeHTTP status code
request_idUnique request identifier for troubleshooting
content_md5MD5 hash of the uploaded content
etagEntity tag (ETag) of the object
hash_crc64CRC-64 hash of the uploaded content
version_idObject version ID (if versioning is enabled)
headers.get("x-oss-server-time")Server processing time in milliseconds

For the complete field reference, see PutObjectResult.

Handle errors

The SDK raises oss.exceptions.OperationError when a request fails. Wrap upload calls in a try-except block to catch and diagnose failures:

try:
    result = client.put_object_from_file(
        oss.PutObjectRequest(
            bucket='examplebucket',
            key='exampledir/exampleobject.txt',
        ),
        '/path/to/local/file.txt',
    )
    print(f'Upload succeeded.'
          f' Status code: {result.status_code},'
          f' Request ID: {result.request_id},'
          f' ETag: {result.etag}')
except oss.exceptions.OperationError as e:
    # The exception contains the HTTP status code, error code, and request ID.
    print(f'Upload failed: {e}')

Common error codes:

Error codeCauseResolution
NoSuchBucketBucket does not existVerify the bucket name and region
AccessDeniedMissing oss:PutObject permissionCheck the RAM policy or bucket policy
EntityTooLargeObject exceeds 5 GBUse multipart upload
InvalidObjectNameObject key violates naming rulesSee naming conventions below

Naming conventions

Bucket naming conventions

  • 3 to 63 characters long

  • Can contain lowercase letters, digits, and hyphens (-)

  • Must start and end with a lowercase letter or digit

  • Cannot contain consecutive hyphens

Object naming conventions

  • UTF-8 encoded

  • 1 to 1,023 characters long

  • Cannot start with a forward slash (/) or a backslash (\)

  • The object key is the full path of the object and cannot contain the bucket name

Complete example

Copy this self-contained script to verify your setup. Replace the placeholder values with your bucket name, object key, and local file path.

import alibabacloud_oss_v2 as oss

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

    # Initialize the client
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = 'cn-hangzhou'
    client = oss.Client(cfg)

    # Upload a local file
    try:
        result = client.put_object_from_file(
            oss.PutObjectRequest(
                bucket='examplebucket',
                key='exampledir/exampleobject.txt',
            ),
            '/path/to/local/file.txt',
        )
        print(f'Upload succeeded.'
              f' Status code: {result.status_code},'
              f' Request ID: {result.request_id},'
              f' ETag: {result.etag}')
    except oss.exceptions.OperationError as e:
        print(f'Upload failed: {e}')

if __name__ == '__main__':
    main()

For additional sample code, see put_object.py.

API reference

put_object(request: PutObjectRequest, **kwargs) -> PutObjectResult
ParameterTypeDescription
requestPutObjectRequestRequest parameters including ACL, forbid_overwrite, and object metadata

What's next

References