Cargue un solo objeto a OSS mediante el método put_object. Tipos de entrada compatibles: cadenas, bytes, caracteres Unicode, flujos de red y archivos locales.
Notas de uso
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization.
Si ya existe un objeto con el mismo nombre en el bucket y usted cuenta con los permisos necesarios, la carga sobrescribirá el objeto existente.
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios de RAM o los roles de RAM bajo una cuenta de Alibaba Cloud no tienen ningún permiso por defecto. La cuenta de Alibaba Cloud o el administrador de la cuenta deben otorgar los permisos de operación mediante RAM policies o Bucket Policy.
Parámetros comunes
La siguiente tabla describe los parámetros comunes para cargar objetos.
|
Parámetro |
Descripción |
|
bucket_name |
Nombre del bucket. El nombre del bucket debe cumplir las siguientes reglas:
|
|
object_name |
Ruta completa del objeto. Esta ruta no puede incluir el nombre del bucket. El nombre del objeto debe cumplir las siguientes reglas:
|
Cargar una cadena
Cargue una cadena en exampleobject.txt dentro de 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']))
Cargar bytes
Cargue bytes en exampleobject.txt dentro de 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')
Cargar un carácter Unicode
Cargue un carácter Unicode en exampleobject.txt dentro de examplebucket. OSS convierte automáticamente los caracteres Unicode a bytes codificados en 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')
Cargar un flujo de red
Cargue un flujo de red en exampleobject.txt dentro de examplebucket. OSS trata el flujo como un objeto iterable y lo carga mediante codificación por fragmentos.
# -*- 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)
Cargar un archivo local
Cargue el archivo local examplefile.txt en examplebucket y guárdelo 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 cargar desde una posición específica de bytes, utilice el método seek(). El siguiente ejemplo comienza desde el 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)
Preguntas frecuentes
¿Cómo obtengo la URL del archivo después de una carga?
El SDK no devuelve la URL del archivo tras la carga. Para obtener la URL, Use a signed URL to download or preview a file.
¿Cómo compruebo si el tamaño del archivo cargado coincide con el del archivo local?
OSS habilita la validación CRC de forma predeterminada durante las cargas y descargas. Si el tamaño del archivo cargado difiere del archivo local, se notifica un error InconsistentError.
-
La validación CRC puede reducir la velocidad de carga. Para priorizar el throughput, deshabilítela:
# -*- 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)
Referencias
Código de ejemplo completo: Ejemplo en GitHub.
Referencia de la API: PutObject.