Téléchargez un seul objet vers OSS à l'aide de la méthode put_object. Les types d'entrée pris en charge sont les chaînes, les octets, les caractères Unicode, les flux réseau et les fichiers locaux.
Remarques sur l'utilisation
Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région qu'OSS, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.
Cette rubrique explique comment créer une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Initialisation.
Si un objet portant le même nom existe déjà dans le bucket et que vous disposez des autorisations requises, le téléchargement écrase l'objet existant.
Autorisations
Par défaut, un compte Alibaba Cloud dispose de toutes les autorisations. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune autorisation par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les autorisations d'opération via des politiques RAM ou une Bucket Policy.
Paramètres courants
Le tableau suivant décrit les paramètres courants pour le téléchargement d'objets.
|
Paramètre |
Description |
|
bucket_name |
Nom du bucket. Le nom du bucket doit respecter les règles suivantes :
|
|
object_name |
Chemin complet de l'objet. Le chemin complet ne doit pas inclure le nom du bucket. Le nom de l'objet doit respecter les règles suivantes :
|
Télécharger une chaîne
Téléchargez une chaîne vers exampleobject.txt dans 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']))
Télécharger des octets
Téléchargez des octets vers exampleobject.txt dans 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')
Télécharger un caractère Unicode
Téléchargez un caractère Unicode vers exampleobject.txt dans examplebucket. OSS convertit automatiquement le caractère Unicode en octets encodés 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')
Télécharger un flux réseau
Téléchargez un flux réseau vers exampleobject.txt dans examplebucket. OSS traite le flux comme un objet itérable et le télécharge avec un encodage par blocs.
# -*- 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)
Télécharger un fichier local
Téléchargez le fichier local examplefile.txt vers examplebucket et enregistrez-le sous le nom 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)
Pour télécharger à partir d'une position d'octet spécifique, utilisez la méthode seek(). L'exemple suivant commence à partir de l'octet 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)
FAQ
Comment obtenir l'URL du fichier après un téléchargement ?
Le SDK ne renvoie pas l'URL du fichier après le téléchargement. Pour obtenir l'URL, consultez Utiliser une URL signée pour télécharger ou prévisualiser un fichier.
Comment vérifier si la taille du fichier téléchargé est identique à celle du fichier local ?
OSS active la validation CRC par défaut lors des téléchargements et des téléchargements descendants. Si la taille du fichier téléchargé diffère de celle du fichier local, une erreur InconsistentError est signalée.
-
La validation CRC peut réduire la vitesse de téléchargement. Pour privilégier le débit, désactivez-la :
# -*- 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)
Références
Exemple de code complet : Exemple GitHub.
Référence API : PutObject.