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_v2installed:pip install alibabacloud-oss-v2An OSS bucket that meets the bucket naming conventions
oss:PutObjectpermission granted through a RAM policy or bucket policyYour AccessKey ID and AccessKey secret stored as environment variables (
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_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 grantedoss:PutObjectaccess. Additional permissions are required for specific features:oss:PutObjectTaggingfor object tagging, andkms:GenerateDataKeyandkms:Decryptfor 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:
| Method | Best for | Input | Advantage |
|---|---|---|---|
put_object_from_file | Local files | File path (string) | Reads in binary mode and handles CRC-64 verification automatically |
put_object | Strings, byte arrays, streams, or any in-memory data | bytes or file-like object | Works with any data source |
For the complete API reference, see put_object.
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 NoneAlternatively, 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.
Common configurations
The following snippets show how to set frequently used options in PutObjectRequest. Combine these parameters with any upload method.
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
| Parameter | Type | Description |
|---|---|---|
bucket | str | Bucket name (required) |
key | str | Object key — the full path excluding the bucket name (required) |
body | bytes or file-like | Object content |
forbid_overwrite | bool | Prevent overwriting an existing object with the same name |
acl | str | Access control list (ACL) for the object. Valid values: private, public-read, public-read-write |
storage_class | str | Storage class. Valid values: Standard, IA (Infrequent Access), Archive, ColdArchive, DeepColdArchive |
content_type | str | MIME type of the object (for example, text/plain, image/jpeg) |
callback | str | Base64-encoded upload callback configuration |
callback_var | str | Base64-encoded custom upload callback variables |
progress_fn | callable | Progress callback for tracking upload progress |
tagging | str | Object tags in URL query-string format (for example, key1=value1&key2=value2) |
server_side_encryption | str | Server-side encryption method. Valid values: AES256, KMS, SM4 |
PutObjectResult fields
Both upload methods return a PutObjectResult with the following fields:
| Field | Description |
|---|---|
status_code | HTTP status code |
request_id | Unique request identifier for troubleshooting |
content_md5 | MD5 hash of the uploaded content |
etag | Entity tag (ETag) of the object |
hash_crc64 | CRC-64 hash of the uploaded content |
version_id | Object 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 code | Cause | Resolution |
|---|---|---|
NoSuchBucket | Bucket does not exist | Verify the bucket name and region |
AccessDenied | Missing oss:PutObject permission | Check the RAM policy or bucket policy |
EntityTooLarge | Object exceeds 5 GB | Use multipart upload |
InvalidObjectName | Object key violates naming rules | See naming conventions below |
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| Parameter | Type | Description |
|---|---|---|
request | PutObjectRequest | Request parameters including ACL, forbid_overwrite, and object metadata |
What's next
Upload objects larger than 5 GB with multipart upload
Control access to objects with RAM policies or bucket policies
Find your region ID in OSS regions and endpoints