Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement simple

Dernière mise à jour :Aug 18, 2026

Utilisez le téléchargement simple pour transférer des objets d'une taille maximale de 5 Go vers OSS lorsque la concurrence élevée n'est pas requise.

Avertissement

Dans un bucket où le service OSS-HDFS est activé, ne téléchargez pas d'objets dans le répertoire de stockage des données .dlsdata/ en utilisant une méthode autre que le service OSS-HDFS lui-même. Cette opération pourrait entraîner un dysfonctionnement du service ou une perte de données.

Méthodes de téléchargement

Avant de commencer, créez un bucket.

Important

En raison d'un changement de politique visant à améliorer la conformité et la sécurité, à compter du 20 mars 2025, les nouveaux utilisateurs d'OSS **doivent utiliser un nom de domaine personnalisé (CNAME) pour effectuer des opérations d'API de données sur les buckets OSS situés dans les régions de Chine continentale. Les points de terminaison publics par défaut sont restreints pour ces opérations. Consultez l'annonce officielle pour obtenir la liste complète des opérations concernées. Si vous accédez à vos données via HTTPS, vous devez associer un certificat SSL valide à votre nom de domaine personnalisé. Cette étape est obligatoire pour l'accès à la console OSS, car la console impose l'utilisation du protocole HTTPS.

Console OSS

  1. Connectez-vous à la console OSS.

  2. Dans le volet de navigation de gauche, cliquez sur Buckets. Sur la page qui s'affiche, cliquez sur le nom du bucket cible.

  3. Dans le volet de navigation de gauche, choisissez Object Management > Objects.

  4. Sur la page Objects, cliquez sur Upload Object.

  5. Dans le panneau Upload Object, sélectionnez les fichiers ou dossiers que vous souhaitez télécharger.

    1. Facultatif : Configurez les options de base.

      Options de base

      Paramètre

      Description

      Upload to

      Définissez le chemin de destination dans le bucket.

      • Current Directory : téléchargez les objets dans le répertoire actuel.

      • Specified Directory : téléchargez vers un répertoire spécifié. Vous devez saisir un nom de répertoire. Si le répertoire n'existe pas, OSS le crée automatiquement.

        Le nom du répertoire doit respecter les exigences suivantes :

        • La longueur du nom doit être comprise entre 1 et 254 caractères et utiliser l'encodage UTF-8.

        • Le nom ne peut pas commencer par une barre oblique (/) ou une barre oblique inverse (\).

        • Le nom ne peut pas contenir de barres obliques (/) consécutives.

        • Le nom ne peut pas être ...

      Object ACL

      Définissez la liste de contrôle d'accès (ACL) de l'objet.

      • Inherited from Bucket : l'objet hérite de l'ACL du bucket.

      • Private (recommandé) : seul le propriétaire de l'objet dispose des autorisations de lecture et d'écriture sur l'objet.

      • Public Read : le propriétaire de l'objet dispose des autorisations de lecture et d'écriture, tandis que les autres utilisateurs, y compris les utilisateurs anonymes, ont un accès en lecture seule. Cette option peut entraîner des fuites de données et une augmentation des frais. Utilisez-la avec prudence.

      • Public Read/Write : tous les utilisateurs, y compris les utilisateurs anonymes, peuvent lire et écrire l'objet. Cette option peut entraîner des fuites de données et une augmentation des frais. Si des utilisateurs malveillants téléchargent des informations illégales, vous pourriez être tenu responsable légalement. Ne sélectionnez cette option que si nécessaire.

      ACL des objets.

      Files to Upload

      Sélectionnez les fichiers ou dossiers à télécharger.

      Cliquez sur Select Files ou Select Folders pour sélectionner des fichiers ou dossiers locaux. Vous pouvez également faire glisser les fichiers ou dossiers cibles vers la zone de téléchargement.

      Pour exclure un fichier du téléchargement, cliquez sur Remove à côté de celui-ci.

      Important
      • Si vous téléchargez un objet portant le même nom qu'un objet existant dans un bucket où le versioning est désactivé, le téléchargement écrase l'objet existant.

      • Si vous téléchargez un objet portant le même nom qu'un objet existant dans un bucket pour lequel le versioning est activé, l'objet téléchargé devient la version actuelle et l'objet existant devient une version précédente.

    2. Facultatif : Configurez les options avancées, telles que la classe de stockage et la méthode de chiffrement côté serveur.

      Options avancées

      Paramètre

      Description

      Storage Class

      Définissez la classe de stockage.

      • Inherited from Bucket : l'objet hérite de la classe de stockage du bucket.

      • Standard : Fournit un service de stockage d'objets hautement fiable, disponible et performant qui prend en charge l'accès fréquent aux données. Il convient à divers cas d'utilisation, tels que les applications sociales et de partage, les grands sites web et l'analyse de big data. La classe de stockage Standard prend en charge le stockage redondant inter-zones (ZRS) et le stockage redondant local (LRS).

      • Infrequent Access : Fournit un stockage d'objets hautement durable à faible coût de stockage. La taille minimale facturée est de 64 Ko et la durée de stockage minimale est de 30 jours. Il prend en charge l'accès aux données en temps réel. L'accès aux données entraîne des frais de récupération. Cette classe de stockage convient aux scénarios professionnels avec une faible fréquence d'accès, comme une à deux fois par mois en moyenne. La classe de stockage Infrequent Access prend en charge ZRS et LRS.

      • Archive Storage : Fournit un stockage d'objets hautement durable à un coût de stockage extrêmement faible. La taille minimale facturée est de 64 Ko et la durée de stockage minimale est de 60 jours. Les données Archive Storage peuvent être consultées après leur restauration, ce qui prend environ une minute, ou directement. Les données restaurées entraînent des frais de récupération, tandis que les données consultées directement entraînent des frais d'accès en temps réel. Archive Storage convient à la conservation des données à long terme, comme pour les archives, les images médicales, les données scientifiques et les séquences vidéo. La classe de stockage Archive Storage prend en charge ZRS et LRS.

      • Cold Archive : Fournit un stockage d'objets hautement durable à un coût inférieur à celui d'Archive Storage. La taille minimale facturée est de 64 Ko et la durée de stockage minimale est de 180 jours. Les données doivent être restaurées avant d'être accessibles. Le temps de restauration dépend de la taille des données et du mode de restauration sélectionné. La restauration entraîne des frais de récupération de données et de requête. Cette classe de stockage convient aux données froides nécessitant un stockage à très long terme, comme les données conservées pour des raisons de conformité, les données brutes accumulées dans les domaines du big data et de l'intelligence artificielle (IA), les actifs multimédias de l'industrie cinématographique et télévisuelle, et les vidéos archivées dans le secteur de l'éducation en ligne. La classe de stockage Cold Archive prend uniquement en charge LRS.

      • Deep Cold Archive : Fournit un stockage d'objets hautement durable à un coût inférieur à celui de Cold Archive. La taille minimale facturée est de 64 Ko et la durée de stockage minimale est de 180 jours. Les données doivent être restaurées avant d'être accessibles. Le temps de restauration dépend de la taille des données et du mode de restauration sélectionné. La restauration entraîne des frais de récupération de données et de requête. Cette classe de stockage convient aux données extrêmement froides nécessitant un stockage ultra-long terme, comme la conservation à long terme des données brutes dans les domaines du big data et de l'IA, la conservation à long terme des données multimédias, les archives réglementaires et de conformité, et le remplacement des bandes magnétiques. La classe de stockage Deep Cold Archive prend uniquement en charge LRS.

      Présentation des classes de stockage.

      Encryption Method

      Définissez la méthode de chiffrement côté serveur.

      • Inherited from Bucket : l'objet hérite de la méthode de chiffrement côté serveur du bucket.

      • SSE-OSS : utilisez des clés gérées par OSS pour le chiffrement. OSS utilise une clé différente pour chiffrer chaque objet. Pour une protection supplémentaire, OSS utilise une clé principale pour chiffrer la clé de chiffrement des données elle-même.

      • KMS : utilisez une clé maître cliente (CMK) par défaut gérée par KMS ou un ID de CMK spécifié pour chiffrer et déchiffrer les données. Voici la description du paramètre CMK :

        • alias/acs/oss(CMK ID) : si vous sélectionnez cette option, OSS utilise la clé de service par défaut pour chiffrer les données dans le bucket et déchiffre automatiquement les données lorsque vous téléchargez des objets depuis le bucket.

        • alias/<cmkname>(CMK ID) : si vous sélectionnez cette option, OSS utilise la clé de service spécifiée pour chiffrer les données dans le bucket et enregistre l'ID de la CMK dans les métadonnées de l'objet chiffré. Lorsqu'un utilisateur disposant des autorisations de déchiffrement télécharge l'objet, celui-ci est automatiquement déchiffré. <cmkname> est un alias facultatif pour la CMK que vous avez spécifié lors de la création de la clé.

          Avant d'utiliser un ID de CMK spécifié, vous devez créer une clé standard ou externe dans la même région que le bucket dans la console KMS. Pour plus d'informations, consultez Créer une CMK.

      • Encryption Algorithm : Seul AES256 est pris en charge.

      User-defined Metadata

      Ajoutez des métadonnées personnalisées à un objet. La taille totale de toutes les entrées ne doit pas dépasser 8 Ko. Chaque clé doit commencer par le préfixe x-oss-meta- et se voir attribuer une valeur, par exemple x-oss-meta-location:hangzhou.

  6. Cliquez sur Upload Object.

    Vous pouvez ensuite consulter la progression du téléchargement de l'objet dans l'onglet Upload Tasks.

Ossbrowser

Avant d'utiliser ossbrowser pour le téléchargement simple, installez ossbrowser 2,0 et connectez-vous à ossbrowser 2,0.

  1. Cliquez sur le nom du bucket de destination.

  2. Cliquez sur Upload, puis sélectionnez les fichiers ou dossiers à télécharger.

    Vous pouvez consulter la progression du téléchargement dans le coin supérieur droit.

SDK Alibaba Cloud

Télécharger un fichier complet

Téléchargez un fichier local vers un bucket spécifié.

Java

Avant de commencer, assurez-vous d'avoir configuré les identifiants d'accès et installé le SDK OSS pour Java V1.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.File;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
        // By default, if the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. 
        String filePath= "D:\\localpath\\examplefile.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Create a PutObjectRequest object. 
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // The following sample code provides an example on how to specify the storage class and ACL of an object when you upload the object: 
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
            
            // Upload the local file. 
            PutObjectResult result = ossClient.putObject(putObjectRequest);           
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Python.

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()

Go

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Go.

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt.
	localFile := "/Users/localpath/exampleobject.txt"

	// Create a request to upload the local file.
	putRequest := &oss.PutObjectRequest{
		Bucket:       oss.Ptr(bucketName),      // Specify the name of the bucket.
		Key:          oss.Ptr(objectName),      // Specify the name of the object.
		StorageClass: oss.StorageClassStandard, // Set the storage class of the object to Standard.
		Acl:          oss.ObjectACLPrivate,     // Set the access control list (ACL) of the object to private.
		Metadata: map[string]string{
			"yourMetadataKey 1": "yourMetadataValue 1", // Specify the metadata of the object.
		},
	}

	// Execute the request to upload the local file.
	result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object from file result:%#v\n", result)
}

Node.js

const OSS = require('ali-oss')
const path=require("path")

const client = new OSS({
  // Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: 'examplebucket',
});

// Custom request headers
const headers = {
  // Specify the storage class of the object.
  'x-oss-storage-class': 'Standard',
  // Specify the access permissions of the object.
  'x-oss-object-acl': 'private',
  // When the file is accessed using its URL, specify that the file is downloaded as an attachment. The downloaded file is named example.txt.
  'Content-Disposition': 'attachment; filename="example.txt"',
  // Set tags for the object. You can set multiple tags at the same time.
  'x-oss-tagging': 'Tag1=1&Tag2=2',
  // Specify whether to overwrite an object that has the same name during a PutObject operation. This parameter is set to true to prevent the object from being overwritten.
  'x-oss-forbid-overwrite': 'true',
};

async function put () {
  try {
    // Specify the full path of the OSS object and the full path of the local file. The full path of the OSS object cannot contain the bucket name.
    // If you do not specify a local path in the full path of the local file, the file is uploaded from the local path of the project to which the sample program belongs.
    const result = await client.put('exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt')
    // Custom headers
    ,{headers}
    );
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

PHP

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
    "file" => ['help' => 'Local path to the file you want to upload.', 'required' => True], // (Required) Specify the path of the local file.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
$file = $options["file"]; // The path of the local file.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Check whether the local file exists.
if (!file_exists($file)) {
    echo "Error: The specified file does not exist." . PHP_EOL; // If the local file does not exist, an error message is displayed and the program is exited.
    exit(1);
}

// Open the local file and prepare for the simple upload task.
// Use fopen to open the local file in read-only mode and convert the file to a stream by using Utils::streamFor.
$body = Oss\Utils::streamFor(fopen($file, 'r'));

// Create a PutObjectRequest object to upload the local file.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = $body; // Specify that the HTTP request body is a file stream.

// Execute the simple upload request.
$result = $client->putObject($request);

// Display the result of the simple upload request.
// Display the HTTP status code, the request ID, and the ETag of the object to check whether the request is successful.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
    'etag:' . $result->etag . PHP_EOL // The ETag of the object, which is used to identify the content of the object.
);

Browser.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <input id="file" type="file" />
    <button id="upload">Upload an Object</button>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
    <script>
      const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: "yourRegion",
        authorizationV4: true,
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // Specify the security token that you obtained from STS. 
        stsToken: "yourSecurityToken",
        // Specify the name of the bucket. 
        bucket: "examplebucket",
      });

      // Select the local file from the drop-down list. Example: <input type="file" id="file" />. 
      let data;
      // Create and specify the Blob data. 
      //const data = new Blob(['Hello OSS']);
      // Create an OSS buffer and specify the content of the OSS buffer. 
      //const data = new OSS.Buffer(['Hello OSS']);

      const upload = document.getElementById("upload");

      async function putObject(data) {
        try {
          // Specify the full path of the object. Do not include the bucket name in the full path. 
          // Specify the object name or the full path of the object to upload data to the current bucket or a specific directory in the bucket. For example, set the object name to exampleobject.txt or the path of the object to exampledir/exampleobject.txt. 
          // You can set the data to files, Blob data, or OSS buffers. 
          const options = {
            meta: { temp: "demo" },
            mime: "json",
            headers: { "Content-Type": "text/plain" },
          };
          const result = await client.put("examplefile.txt", data, options);
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }

      upload.addEventListener("click", () => {
        const data = file.files[0];
        putObject(data);
      });
    </script>
  </body>
</html>

.NET

using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
var localFilename = "D:\\localpath\\examplefile.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Upload the local file. 
    client.PutObject(bucketName, objectName, localFilename);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}

Harmony

import Client, { RequestError } from '@aliyun/oss';

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the STS temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the security token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
  // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'oss-cn-hangzhou',
});

const bucket = 'yourBucketName'; // Replace with the name of the bucket you want to use.

const key = 'yourObjectName'; // Replace with the name of the object (file) you want to upload.

const putObject = async () => {
  try {
    // Call the putObject method to upload data to the specified bucket and key, passing the data as a parameter.
    const res = await client.putObject({
      bucket, // The bucket name.
      key, // The object (file) name.
      data: 'hello world' // The data to upload. In this case, a simple string.
    });

    // Print the upload result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch exceptions that occur during the request.
    if (err instanceof RequestError) {
      // If the error is a known type, print the error code, message, request ID, status code, EC code, and other information.
      console.log('code: ', err.code);
      console.log('message: ', err.message);
      console.log('requestId: ', err.requestId);
      console.log('status: ', err.status);
      console.log('ec: ', err.ec);
    } else {
      // Print other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
}

// Call the putObject function to perform the upload operation.
putObject();

Android

// Create an upload request.
// Specify the bucket name (for example, examplebucket), the full path of the object (for example, exampledir/exampleobject.txt), and the full path of the local file (for example, /storage/emulated/0/oss/examplefile.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

// Setting file metadata is optional.
 ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("application/octet-stream"); // Set the content type.
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // Verify the MD5 hash.
// Set the access permissions of the object to private.
metadata.setHeader("x-oss-object-acl", "private");
// Set the storage class of the object to Standard.
metadata.setHeader("x-oss-storage-class", "Standard");
// Prevent overwriting an object with the same name.
// metadata.setHeader("x-oss-forbid-overwrite", "true");
// Specify object tags. You can specify multiple tags.
// metadata.setHeader("x-oss-tagging", "a:1");
// Specify the server-side encryption algorithm that OSS uses to create the destination object.
// metadata.setHeader("x-oss-server-side-encryption", "AES256");
// Specifies the customer master key (CMK) managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
// metadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****");

put.setMetadata(metadata);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Client exception, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // Server exception.
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

iOS

OSSPutObjectRequest * put = [OSSPutObjectRequest new];

// Specify the bucket name. For example, examplebucket.
put.bucketName = @"examplebucket";
// Specify the full path of the object. For example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
put.objectKey = @"exampledir/exampleobject.txt";
put.uploadingFileURL = [NSURL fileURLWithPath:@"<filePath>"];
// put.uploadingData = <NSData *>; // Directly upload NSData.

// (Optional) Set the upload progress.
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    // The current upload length, the total uploaded length, and the total length to upload.
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
// Configure optional fields.
// put.contentType = @"application/octet-stream";
// Set Content-MD5.
// put.contentMd5 = @"eB5eJF1ptWaXm4bijSPyxw==";
// Set the codec of the object.
// put.contentEncoding = @"identity";
// Set the display format of the object.
// put.contentDisposition = @"attachment";
// You can set object metadata or HTTP headers when you upload a file.
// NSMutableDictionary *meta = [NSMutableDictionary dictionary];
// Set the file metadata.
// [meta setObject:@"value" forKey:@"x-oss-meta-name1"];
// Set the access permissions of the object to private.
// [meta setObject:@"private" forKey:@"x-oss-object-acl"];
// Set the storage class of the object to Standard.
// [meta setObject:@"Standard" forKey:@"x-oss-storage-class"];
// Overwrite the destination object that has the same name.
// [meta setObject:@"true" forKey:@"x-oss-forbid-overwrite"];
// Specify object tags. You can specify multiple tags.
// [meta setObject:@"a:1" forKey:@"x-oss-tagging"];
// Specify the server-side encryption algorithm that OSS uses to create the destination object.
// [meta setObject:@"AES256" forKey:@"x-oss-server-side-encryption"];
// The customer master key (CMK) that is managed by KMS. This parameter is valid only when x-oss-server-side-encryption is set to KMS.
// [meta setObject:@"9468da86-3509-4f8d-a61e-6eab1eac****" forKey:@"x-oss-server-side-encryption-key-id"];
// put.objectMeta = meta;
OSSTask * putTask = [client putObject:put];

[putTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"upload object success!");
    } else {
        NSLog(@"upload object failed, error: %@" , task.error);
    }
    return nil;
}];
// waitUntilFinished blocks the current thread, but does not block the upload process.
// [putTask waitUntilFinished];
// [put cancel];

C++

#include <alibabacloud/oss/OssClient.h>
#include <fstream>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of 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. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Enter the bucket name. For example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Enter the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
    /* Enter the full path of the local file. For example, D:\\localpath\\examplefile.txt. In this example, localpath is the local directory where the examplefile.txt file is stored. */
    std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("D:\\localpath\\examplefile.txt", std::ios::in | std::ios::binary);
    PutObjectRequest request(BucketName, ObjectName, content);

    /* (Optional) The following example shows how to set the access control list (ACL) to private and the storage class to Standard. */
    //request.MetaData().addHeader("x-oss-object-acl", "private");
    //request.MetaData().addHeader("x-oss-storage-class", "Standard");

    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /* Handle the exception. */
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
        return 0;
}

C

#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of 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. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content = "More than just cloud.";
/* Set yourRegion to the region ID of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region ID to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specifies whether a CNAME is used. 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool for memory management is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, which indicates that the memory pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter contains global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client option oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_list_t buffer;
    aos_buf_t *content = NULL;
    aos_table_t *headers = NULL;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    aos_list_init(&buffer);
    content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content));
    aos_list_add_tail(&content->node, &buffer);
    /* Upload the file. */
    resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, &buffer, headers, &resp_headers);
    /* Check whether the upload is successful. */
    if (aos_status_is_ok(resp_status)) {
        printf("put object from buffer succeeded\n");
    } else {
        printf("put object from buffer failed\n");      
    }
    /* Release the memory pool. This releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Ruby

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # Set the endpoint. This example uses the China (Hangzhou) region. Specify the endpoint for your actual region.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Upload the file.
bucket.put_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')

Télécharger une chaîne

Téléchargez le contenu d'une chaîne en mémoire sous forme d'objet.

Java

Avant de commencer, assurez-vous d'avoir configuré les identifiants d'accès et installé le SDK OSS pour Java V1.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance.
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build()
        
        try {
            // Specify the string that you want to upload. 
            String content = "Hello OSS, hello world";

            // Create a PutObjectRequest object. 
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));

            // The following sample code provides an example on how to specify the storage class and access control list (ACL) of an object when you upload the object: 
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
           
            // Upload the string. 
            PutObjectResult result = ossClient.putObject(putObjectRequest);            
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}   

Python

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Python.

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.

Go

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Go.

package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the string that you want to upload.
	body := strings.NewReader("hi oss")

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
		Body:   body,                // The string that you want to upload.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

PHP

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Specify the content that you want to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest object to upload the local file.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request-> body=Oss\Utils::streamFor($data); // Specify that the HTTP request body is a binary stream.

// Execute the simple upload request.
$result = $client->putObject($request);

// Display the result of the simple upload request.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL . // The request ID.
    'etag: %s' . PHP_EOL, // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Node.js

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of your bucket. 
  bucket: 'yourbucketname',
});

async function putBuffer () {
  try {
    const result = await client.put('object-name', new Buffer.from('hello world'));
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putBuffer();

.NET

using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the string that you want to upload. 
var objectContent = "More than just cloud.";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
    MemoryStream requestContent = new MemoryStream(binaryData);
    // Upload the object. 
    client.PutObject(bucketName, objectName, requestContent);
    Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Put object failed, {0}", ex.Message);
}

Télécharger un tableau d'octets

Téléchargez des données binaires à partir d'un tableau d'octets. Cette méthode est utile lorsque vous devez traiter les données avant le téléchargement.

Python

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Python.

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.

Go

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Go.

package main

import (
	"bytes"
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the byte array that you want to upload.
	body := bytes.NewReader([]byte("yourObjectValueByteArray"))

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
		Body:   body,                // The string that you want to upload.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

Android

byte[] uploadData = new byte[100 * 1024];
new Random().nextBytes(uploadData);

// Create an upload request.
// Specify the bucket name (for example, examplebucket) and the full path of the object (for example, exampledir/exampleobject.txt).
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", uploadData);

try {
    PutObjectResult putResult = oss.putObject(put);

    Log.d("PutObject", "UploadSuccess");
    Log.d("ETag", putResult.getETag());
    Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
    // Client exception, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // Server exception.
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

Téléchargement d'un flux de fichier

Lisez les données depuis un fichier local ou la mémoire, puis téléchargez-les à l'aide d'un flux de fichier.

Java

Avant de commencer, assurez-vous d'avoir configuré les identifiants d'accès et installé le SDK OSS pour Java V1.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. 
        // If you do not specify the path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
        String filePath= "D:\\localpath\\examplefile.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance.
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            InputStream inputStream = new FileInputStream(filePath);
            // Create a PutObjectRequest object. 
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // Create a PutObject request. 
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
} 

Node.js

const OSS = require('ali-oss');
const fs = require('fs');
const client = new OSS({
  // Specify the region where the bucket is located. For example, for China (Hangzhou), set region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name, for example, examplebucket.
  bucket: 'examplebucket',
});

async function putStream () {
  try {
    // By default, the SDK uses chunked encoding and sends an HTTP PUT request when you call the putStream operation.
    // Specify the full path of the local source file.
    // If you omit the local path, the file is uploaded from the script's directory.
    let stream = fs.createReadStream('D:\\localpath\\examplefile.txt');
    // Specify the full path of the object, for example, 'exampledir/exampleobject.txt'. The full path cannot contain the bucket name.
    let result = await client.putStream('exampledir/exampleobject.txt', stream);    

    // To disable chunked encoding, specify the contentLength parameter in the options.
    // let stream = fs.createReadStream('D:\\localpath\\examplefile.txt');
    // let size = fs.statSync('D:\\localpath\\examplefile.txt').size;
    // let result = await client.putStream(
    // The stream parameter can be any Readable Stream object, such as a file stream or a network stream.
    // 'exampledir/exampleobject.txt', stream, {contentLength: size}); 
    console.log(result); 
  } catch (e) {
    console.log(e)
  }
}

putStream();

Ruby

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # This example uses the China (Hangzhou) endpoint. Replace it with the endpoint for your region.  
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run this sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

# Specify the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Specify the full path of the object. Do not include the bucket name in the full path. For example, exampleobject.txt.
bucket.put_object('exampleobject.txt') do |stream|
  100.times { |i| stream << i.to_s }
end

Téléchargement d'un flux réseau

Transférez directement les données depuis une source réseau vers OSS sans les enregistrer localement.

Java

Avant de commencer, assurez-vous d'avoir configuré les identifiants d'accès et installé le SDK OSS pour Java V1.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.InputStream;
import java.net.URL;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the URL of the network stream. 
        String url = "https://www.aliyun.com/";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Create an OSSClient instance.
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            InputStream inputStream = new URL(url).openStream();
            // Create a PutObjectRequest object. 
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // Create a PutObject request. 
            PutObjectResult result = ossClient.putObject(putObjectRequest);            
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}             

Python

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Python.

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.

Go

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Go.

package main

import (
	"context"
	"flag"
	"io"
	"log"
	"net/http"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the network stream that you want to upload.
	resp, err := http.Get("https://www.aliyun.com/")
	if err != nil {
		log.Fatalf("Failed to fetch URL: %v", err)
	}
	defer resp.Body.Close()

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key: oss.Ptr(objectName),        // The name of the object.
		Body:   io.Reader(resp.Body), // The network stream that you want to upload.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

Node.js

const OSS = require("ali-oss");
const fs = require("fs");
const urllib = require("urllib"); 

const client = new OSS({  
  // Specify the region where the bucket is located. For example, for China (Hangzhou), set region to oss-cn-hangzhou.
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name, for example, examplebucket.
  bucket: 'examplebucket',
});

// Specify the URL of the network stream.
const url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/en-US/20220908/cbgh/image_processing_example.jpg";
// Import the Duplex stream.
// The stream parameter can be any Readable Stream object, such as a file stream or a network stream.
const Duplex = require("stream").Duplex;
// Instantiate a Duplex stream.
let stream = new Duplex();

urllib.request(url, (err, data, res) => {
  if (!err) {
    // Push data into the Duplex stream.
    stream.push(data);
    stream.push(null);

    client
      // Specify the full path of the object, for example, 'example.png'. The full path cannot contain the bucket name.
      .putStream("example.png", stream)
      .then((r) => console.log(r))
      .catch((e) => console.log(e));
  }
});

PHP

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Query the content of the network file.
$url = 'https://www.aliyun.com/';
$response = file_get_contents($url);

// Create a PutObjectRequest object to upload the local file.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = Oss\Utils::streamFor($response); // Specify that the HTTP request body is a binary stream.

// Execute the simple upload request.
$result = $client->putObject($request);

// Display the result of the simple upload request.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL . // The request ID.
    'etag: %s' . PHP_EOL, // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Barre de progression du téléchargement

Suivez la progression du téléchargement en temps réel.

Java

Avant de commencer, assurez-vous d'avoir configuré les identifiants d'accès et installé le SDK OSS pour Java V1.

Barre de progression du téléchargement Java.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;

// Use the ProgressListener method to use the progress bar.
public class PutObjectProgressListenerDemo implements ProgressListener {
    private long bytesWritten = 0;
    private long totalBytes = -1;
    private boolean succeed = false;

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir\exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. 
        String pathName = "D:\\localpath\\examplefile.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Specify the parameters of the progress bar when you upload the object. In this example, PutObjectProgressListenerDemo specifies the name of the class that you want to call. Replace it with an actual class name. 
            ossClient.putObject(new PutObjectRequest(bucketName,objectName, new File(pathName)).
                    <PutObjectRequest>withProgressListener(new PutObjectProgressListenerDemo()));
            // Specify the parameters of the progress bar when you download the object. In this example, GetObjectProgressListenerDemo specifies the name of the class that you want to call. Replace it with an actual class name. 
//            ossClient.getObject(new GetObjectRequest(bucketName,objectName).
//                    <GetObjectRequest>withProgressListener(new GetObjectProgressListenerDemo()));

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public boolean isSucceed() {
        return succeed;
    }

    // Rewrite the callback method to use the progress bar. The following sample code provides an example: 
    @Override
    public void progressChanged(ProgressEvent progressEvent) {
        long bytes = progressEvent.getBytes();
        ProgressEventType eventType = progressEvent.getEventType();
        switch (eventType) {
            case TRANSFER_STARTED_EVENT:
                System.out.println("Start to upload......");
                break;
            case REQUEST_CONTENT_LENGTH_EVENT:
                this.totalBytes = bytes;
                System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
                break;
            case REQUEST_BYTE_TRANSFER_EVENT:
                this.bytesWritten += bytes;
                if (this.totalBytes != -1) {
                    int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
                    System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
                } else {
                    System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
                }
                break;
            case TRANSFER_COMPLETED_EVENT:
                this.succeed = true;
                System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
                break;
            case TRANSFER_FAILED_EVENT:
                System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
                break;
            default:
                break;
        }
    }
}

Go

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Go.

package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt.
	localFile := "/Users/localpath/exampleobject.txt"

	// Create a request to upload the local file.
	putRequest := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
		ProgressFn: func(increment, transferred, total int64) {
			fmt.Printf("increment:%v, transferred:%v, total:%v\n", increment, transferred, total)
		}, // Specify a progress callback function that is used to query the upload progress.
	}

	// Execute the request to upload the local file.
	result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
	if err != nil {
		log.Fatalf("failed to put object from file %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object from file result:%#v\n", result)
}

PHP

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help";
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.

// Obtain access credentials from the EnvironmentVariableCredentialsProvider variables.
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are correctly configured.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.

// If the endpoint parameter is provided, specify a custom domain name.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Specify the data content that you want to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest request and specify the bucket name and object name in the request.
$request = new Oss\Models\PutObjectRequest($bucket, $key);

// Convert the data content to a stream object.
$request->body = Oss\Utils::streamFor($data);

// Specify the upload progress callback function.
$request->progressFn = function (int $increment, int $transferred, int $total) {
    echo sprint("Uploaded:%d" . PHP_EOL, $transferred); // The number of uploaded bytes.
    echo sprint("This upload:%d" . PHP_EOL, $increment); // The number of uploaded incremental bytes.
    echo sprint("Total data:%d" . PHP_EOL, $total); // The size of the total object.
    echo '-------------------------------------------'. PHP_EOL; // The dotted line delimiter.
};

// Use the putObject method to upload the local file.
$result = $client->putObject($request);

// Display the result of the simple upload request.
printf(
    'status code: %s' . PHP_EOL, $result->statusCode . // The returned HTTP status code.
    'request id: %s' . PHP_EOL, $result->requestId . // The request ID.
    'etag: %s' . PHP_EOL, $result->etag // The ETag of the object.
);

.NET

using System;
using System.IO;
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;
namespace PutObjectProgress
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.PutObjectProgress();
            Console.ReadKey();
        }
        public static void PutObjectProgress()
        {
            // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
            var endpoint = "yourEndpoint";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
            var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
            // Specify the name of the bucket. 
            var bucketName = "yourBucketName";
            // Specify the full path of the object. Do not include the bucket name in the full path. 
            var objectName = "yourObjectName";
            // Specify the full path of the local file to upload. In this example, the path is set to D:\\localpath\\examplefile.txt. The local named examplefile.txt is stored in the D:\\localpath directory. 
            var localFilename = "yourLocalFilename";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            const string region = "cn-hangzhou";
            // Create a ClientConfiguration instance and modify the default parameters based on your requirements.
            var conf = new ClientConfiguration();
            // Use the signature algorithm V4.
            conf.SignatureVersion = SignatureVersion.V4;
            
            // Create an OSSClient instance.
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
            client.SetRegion(region);
            // Upload the object with the specified progress bar displayed. 
            try
            {
                using (var fs = File.Open(localFilename, FileMode.Open))
                {
                    var putObjectRequest = new PutObjectRequest(bucketName, objectName, fs);
                    putObjectRequest.StreamTransferProgress += streamProgressCallback;
                    client.PutObject(putObjectRequest);
                }
                Console.WriteLine("Put object:{0} succeeded", objectName);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        // Obtain the progress of the upload task. 
        private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
        {
            System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ",
                args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes);
        }
    }
}

Android

// Create an upload request.
// Specify the bucket name (for example, examplebucket), the full path of the object (for example, exampledir/exampleobject.txt), and the full path of the local file (for example, /storage/emulated/0/oss/examplefile.txt).
// Do not include the bucket name in the full path of the object.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

// Set the progress callback function to display the progress bar.
put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
    @Override
    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
        // currentSize is the size of the uploaded part. Unit: bytes.
        // totalSize is the total size of the file to upload. Unit: bytes.
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

// Upload the file asynchronously.
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");
        Log.d("ETag", result.getETag());
        Log.d("RequestId", result.getRequestId());
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Request exceptions.
        if (clientExcepion != null) {
            // Client exceptions, such as network exceptions.
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Service exceptions.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// task.cancel(); // Cancels the task.
// task.waitUntilFinished(); // Waits for the task to complete.

C++

#include <alibabacloud/oss/OssClient.h>
#include <fstream>
using namespace AlibabaCloud::OSS;

void ProgressCallback(size_t increment, int64_t transfered, int64_t total, void* userData)
{
    // increment: the size of data sent in this callback.
    // transfered: the size of data that has been uploaded.
    // total: the total size of the file to upload.
    std::cout << "ProgressCallback[" << userData << "] => " <<
    increment <<" ," << transfered << "," << total << std::endl;
}

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of 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. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
  
    /* Set yourLocalFilename to the full path of the local file. */
    std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("yourLocalFilename", std::ios::in|std::ios::binary);
    PutObjectRequest request(BucketName, ObjectName, content);
  
    TransferProgress progressCallback = { ProgressCallback , nullptr };
    request.setTransferProgress(progressCallback);
   
    /* Upload the file. */
    auto outcome = client.PutObject(request);

    if (!outcome.isSuccess()) {
        /* Handle the exception. */
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

iOS

OSSPutObjectRequest * put = [OSSPutObjectRequest new];
// Specify the name of the bucket. Example: examplebucket. 
put.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
put.objectKey = @"exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. 
// By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. 
put.uploadingFileURL = [NSURL fileURLWithPath:@"filePath"];
// Configure the progress callback function to display the progress bar. 
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    // Specify the number of bytes that are being uploaded, the total number of bytes that are uploaded, and the total number of bytes that you want to upload. 
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask * putTask = [client putObject:put];
[putTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"upload object success!");
    } else {
        NSLog(@"upload object failed, error: %@" , task.error);
    }
    return nil;
}];
// Implement synchronous blocking to wait for the task to complete. 
// [putTask waitUntilFinished]; 

C

#include "oss_api.h"
#include "aos_http_io.h"
/* Replace yourEndpoint with the Endpoint of 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. */
const char *endpoint = "yourEndpoint";

/* Replace with your bucket name, for example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Replace with the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Replace with the full path of the local file. */
const char *local_filename = "yourLocalFilename";
/* Replace yourRegion with the ID of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region ID to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */    
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use a CNAME. 0 indicates that a CNAME is not used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
void percentage(int64_t consumed_bytes, int64_t total_bytes) 
{
    assert(total_bytes >= consumed_bytes);
    printf("%%%" APR_INT64_T_FMT "\n", consumed_bytes * 100 / total_bytes);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool (pool) is used for memory management and is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a new memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter contains global configurations, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory for options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_string_t file;   
    aos_list_t resp_body;
    aos_table_t *resp_headers = NULL;
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    aos_str_set(&file, local_filename);
    /* Upload with a progress bar. */
    resp_status = oss_do_put_object_from_file(oss_client_options, &bucket, &object, &file, NULL, NULL, percentage, &resp_headers, &resp_body);
    if (aos_status_is_ok(resp_status)) {
        printf("put object from file succeeded\n");
    } else {
        printf("put object from file failed\n");
    }
    /* Release the memory pool. This releases the memory allocated for various resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Upload callback

Après le téléchargement, utilisez un callback pour notifier votre serveur d'applications afin qu'il effectue un traitement ultérieur. Callback.

Java

Avant de commencer, assurez-vous d'avoir configuré les identifiants d'accès et installé le SDK OSS Java V1.

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.ByteArrayInputStream;

public class Demo {

    public static void main(String[] args) throws Exception{
        // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
        String objectName = "exampledir/exampleobject.txt";
        // Specify the address of the server to which the callback request is sent. Example: https://example.com:23450. 
        String callbackUrl = "yourCallbackServerUrl";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            String content = "Hello OSS";
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,new ByteArrayInputStream(content.getBytes()));

            // Configure upload callback parameters.
            Callback callback = new Callback();
            callback.setCallbackUrl(callbackUrl);
            // (Optional) Specify the CallbackHost field in the callback request header. 
            // callback.setCallbackHost("yourCallbackHost");
            
            // Set the callback request body in JSON format and define placeholder variables within. 
            callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
            callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object},\\\"mimeType\\\":${mimeType},\\\"size\\\":${size},\\\"my_var1\\\":${x:var1},\\\"my_var2\\\":${x:var2}}");

            // Configure custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:. 
            callback.addCallbackVar("x:var1", "value1");
            callback.addCallbackVar("x:var2", "value2");
            putObjectRequest.setCallback(callback);

            // Perform the upload operation.
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

            // Read the message content returned from the upload callback. 
            byte[] buffer = new byte[1024];
            putObjectResult.getResponse().getContent().read(buffer);
            // You must close the obtained stream after the data is read. Otherwise, connection leaks may occur. Consequently, no connections are available and an exception occurs. 
            putObjectResult.getResponse().getContent().close();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Throwable ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Python.

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()

Go

Avant de commencer, assurez-vous d'avoir configuré les identifiants et installé le SDK OSS pour Go.

package main

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSSClient instance.
	client := oss.NewClient(cfg)

	// Specify the callback parameters.
	callbackMap := map[string]string{
		"callbackUrl":      "http://example.com:23450",                                                        // Specify the URL of the callback server. Example: https://example.com:23450.
		"callbackBody":     "bucket=${bucket}&object=${object}&size=${size}&my_var_1=${x:my_var1}&my_var_2=${x:my_var2}", // Specify the callback request body.
		"callbackBodyType": "application/x-www-form-urlencoded",                                                          // Specify the type of the callback request body.
	}

	// Convert the configurations of the callback parameters to a JSON string and encode the string in Base64 to pass the callback configurations.
	callbackStr, err := json.Marshal(callbackMap)
	if err != nil {
		log.Fatalf("failed to marshal callback map: %v", err)
	}
	callbackBase64 := base64.StdEncoding.EncodeToString(callbackStr)

	callbackVarMap := map[string]string{}
	callbackVarMap["x:my_var1"] = "thi is var 1"
	callbackVarMap["x:my_var2"] = "thi is var 2"
	callbackVarStr, err := json.Marshal(callbackVarMap)
	if err != nil {
		log.Fatalf("failed to marshal callback var: %v", err)
	}
	callbackVarBase64 := base64.StdEncoding.EncodeToString(callbackVarStr)
	// Specify the string that you want to upload.
	body := strings.NewReader("Hello, OSS!") // The string that you want to upload.

	// Create a request to upload the local file.
	request := &oss.PutObjectRequest{
		Bucket:      oss.Ptr(bucketName),        // The name of the bucket.
		Key:         oss.Ptr(objectName),        // The name of the object.
		Body:        body,                       // The object content.
		Callback:    oss.Ptr(callbackBase64),    // The callback parameters.
		CallbackVar: oss.Ptr(callbackVarBase64),
	}

	// Execute the request to upload the local file.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the result of the object upload operation.
	log.Printf("put object result:%#v\n", result)
}

PHP

<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Specify the information about the callback server.
// Specify the callback URL, which is the address of the server that receives the callback request.
// Specify the callback host, which is the hostname of the callback server.
// Specify the callback body, which is the template that is used to specify the callback content. A dynamic placeholder is supported.
// Specify the type of the callback body, which is the format of the callback content.
$callback = base64_encode(json_encode(array(
    'callbackUrl' => yourCallbackServerUrl, // Replace yourCallbackServerUrl with the actual callback server URL.
    'callbackHost' => 'CallbackHost', // Replace CallbackHost with the actual callback server hostname.
    'callbackBody' => 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}',
    'callbackBodyType' => "application/x-www-form-urlencoded", // Specify the format of the callback content.
)));

// Specify custom variables to pass additional information in the callback.
$callbackVar = base64_encode(json_encode(array(
    'x:var1' => "value1", // Specify the first custom variable.
    'x:var2' => 'value2', // Specify the second custom variable.
)));

// Create a PutObjectRequest object to upload the local file.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->callback = $callback; // Specify callback information.
$request->callbackVar = $callbackVar; // Specify the custom variables.

// Execute the simple upload request.
$result = $client->putObject($request);

// Display the result of the simple upload request.
// Display the HTTP status code, the request ID, and the callback result to check whether the request is successful.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
    'callback result:' . var_export($result->callbackResult, true) . PHP_EOL // The details of the callback result.
);

.NET

using System;
using System.IO;
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
namespace Callback
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.PutObjectCallback();
            Console.ReadKey();
        }
        public static void PutObjectCallback()
        {
            // Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
            var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
            var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
            // Specify the bucket name, such as examplebucket.
            var bucketName = "examplebucket";
            // Specify the full path of the object, such as exampledir/exampleobject.txt. The full path cannot contain the bucket name.
            var objectName = "exampledir/exampleobject.txt";
           // Specify the full path of the local file, such as D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the default path of the project.
            var localFilename = "D:\\localpath\\examplefile.txt";
            // Set the callback server URL, such as https://example.com:23450.
            const string callbackUrl = "yourCallbackServerUrl";
            // Set the value of the request body for the callback.
            const string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&" +
                                        "my_var1=${x:var1}&my_var2=${x:var2}";
            //  Specify the Endpoint of 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.
            const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
            const string region = "cn-hangzhou";
            // Create a ClientConfiguration instance and modify the default parameters as needed.
            var conf = new ClientConfiguration();
            // Set the signature version to V4.
            conf.SignatureVersion = SignatureVersion.V4;

            // Create an OssClient instance.
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
            client.SetRegion(region);
            try
            {
                string responseContent = "";
                var metadata = BuildCallbackMetadata(callbackUrl, callbackBody);
                using (var fs = File.Open(localFilename, FileMode.Open))
                {
                    var putObjectRequest = new PutObjectRequest(bucketName, objectName, fs, metadata);
                    var result = client.PutObject(putObjectRequest);
                    responseContent = GetCallbackResponse(result);
                }
                Console.WriteLine("Put object:{0} succeeded, callback response content:{1}", objectName, responseContent);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        // Configure the upload callback.
        private static ObjectMetadata BuildCallbackMetadata(string callbackUrl, string callbackBody)
        {
            string callbackHeaderBuilder = new CallbackHeaderBuilder(callbackUrl, callbackBody).Build();
            string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().
                AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build();
            var metadata = new ObjectMetadata();
            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder);
            return metadata;
        }
        // Read the message returned from the upload callback.
        private static string GetCallbackResponse(PutObjectResult putObjectResult)
        {
            string callbackResponse = null;
            using (var stream = putObjectResult.ResponseStream)
            {
                var buffer = new byte[4 * 1024];
                var bytesRead = stream.Read(buffer, 0, buffer.Length);
                callbackResponse = Encoding.Default.GetString(buffer, 0, bytesRead);
            }
            return callbackResponse;
        }
    }
}

Node.js

const OSS = require("ali-oss");

var path = require("path");

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: "yourregion",
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: "examplebucket",
});

const options = {
  callback: {
    // Specify the address of the callback server that receives the callback request. Example: http://oss-demo.aliyuncs.com:23450. 
    url: "http://oss-demo.aliyuncs.com:23450",
    // (Optional) Specify the Host field included in the callback request header. 
    //host: 'yourCallbackHost',
    // Specify the body of the callback request. 
    body: "bucket=${bucket}&object=${object}&var1=${x:var1}&var2=${x:var2}",
    // Specify Content-Type in the callback request. 
    contentType: "application/x-www-form-urlencoded",
    // Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
    callbackSNI: true,
    // Configure custom parameters for the callback request. 
    customValue: {
      var1: "value1",
      var2: "value2",
    },
  },
};

async function put() {
  try {
    // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. 
    // By default, if you do not specify the path of the local file, the file is uploaded from the local path of the project to which the sample program belongs. 
    let result = await client.put(
      "exampleobject.txt",
      path.normalize("/localpath/examplefile.txt"),
      options
    );
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

Ruby

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # The China (Hangzhou) region is used as an example for the endpoint. Specify the endpoint based on your region.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name, for example, examplebucket.
bucket = client.get_bucket('examplebucket')

callback = Aliyun::OSS::Callback.new(
  url: 'http://oss-demo.aliyuncs.com:23450',
  query: {user: 'put_object'},
  body: 'bucket=${bucket}&object=${object}'
)

begin
  bucket.put_object('files/hello', file: '/tmp/x', callback: callback)
rescue Aliyun::OSS::CallbackError => e
  puts "Callback failed: #{e.message}"
end

Browser.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>

  <body>
    <button id="submit">Upload Callback</button>
    <!--Import the SDK file-->
    <script
      type="text/javascript"
      src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js"
    ></script>
    <script type="text/javascript">
      const client = new OSS({
        // Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set yourRegion to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from the Security Token Service (STS).
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token (SecurityToken) obtained from the STS service.
        stsToken: "yourSecurityToken",
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
      });

      const options = {
        callback: {
          // The server address for the callback request. The address must be an Internet URL.
          url: "http://examplebucket.aliyuncs.com:23450",
          // The value of Host in the callback request header. This is the Host value configured on your server.
          // host: 'yourHost',
          // The value of the request body for the callback.
          body: "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&var1=${x:var1}&var2=${x:var2}",
          // The Content-Type of the callback request.
          // contentType: 'application/x-www-form-urlencoded',
          // Specifies whether OSS sends a Server Name Indication (SNI) to the origin URL specified by callbackUrl when the client initiates a callback request.
          callbackSNI: true,
          // The custom parameters for the callback request.
          customValue: {
            var1: "value1",
            var2: "value2",
          },
        },
      };
      // Get the DOM.
      const submit = document.getElementById("submit");
      // Upload callback.
      submit.addEventListener("click", () => {
        client
          .put("example.txt", new Blob(["Hello World"]), options)
          .then((r) => console.log(r));
      });
    </script>
  </body>
</html>

Android

// Create an upload request.
// Specify the bucket name, the full path of the object, and the full path of the local file. For example, examplebucket, exampledir/exampleobject.txt, and /storage/emulated/0/oss/examplefile.txt.
// The full path of the object cannot contain the bucket name.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");

put.setCallbackParam(new HashMap<String, String>() {
    {
        put("callbackUrl", "http://oss-demo.aliyuncs.com:23450");
        put("callbackHost", "yourCallbackHost");
        put("callbackBodyType", "application/json");
        put("callbackBody", "{\"mimeType\":${mimeType},\"size\":${size}}");
    }
});

OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
    @Override
    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
        Log.d("PutObject", "UploadSuccess");

        // This value contains data only if servercallback is set.
        String serverCallbackReturnJson = result.getServerCallbackReturnBody();

        Log.d("servercallback", serverCallbackReturnJson);
    }

    @Override
    public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
        // Handle exceptions.
    }
});
        

C++

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";
    /* Specify the URL of your callback server. */
    std::string ServerName = "https://example.aliyundoc.com:23450";

     /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "Thank you for using Alibaba Cloud Object Storage Service!";

    /* Set the upload callback parameters. */
    std::string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var1=${x:var1}";
    ObjectCallbackBuilder builder(ServerName, callbackBody, "", ObjectCallbackBuilder::Type::URL);
    std::string value = builder.build();
    ObjectCallbackVariableBuilder varBuilder;
    varBuilder.addCallbackVariable("x:var1", "value1");
    std::string varValue = varBuilder.build();
    PutObjectRequest request(BucketName, ObjectName, content);
    request.MetaData().addHeader("x-oss-callback", value);
    request.MetaData().addHeader("x-oss-callback-var", varValue);
    auto outcome = client.PutObject(request);

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

iOS

OSSPutObjectRequest * request = [OSSPutObjectRequest new];
// Specify the name of the bucket. Example: examplebucket. 
request.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
request.objectKey = @"exampledir/exampleobject.txt";
request.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
// Configure callback parameters.
request.callbackParam = @{
                          @"callbackUrl": @"<your server callback address>",
                          @"callbackBody": @"<your callback body>"
                          };
// Specify custom variables. 
request.callbackVar = @{
                        @"<var1>": @"<value1>",
                        @"<var2>": @"<value2>"
                        };
request.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask * task = [client putObject:request];
[task continueWithBlock:^id(OSSTask *task) {
    if (task.error) {
        OSSLogError(@"%@", task.error);
    } else {
        OSSPutObjectResult * result = task.result;
        NSLog(@"Result - requestId: %@, headerFields: %@, servercallback: %@",
              result.requestId,
              result.httpResponseHeaderFields,
              result.serverReturnJsonString);
    }
    return nil;
}];
// Implement synchronous blocking to wait for the task to complete. 
// [task waitUntilFinished]; 

C

#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";

/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot include the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content = "More than just cloud.";
/* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */    
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specifies whether a canonical name (CNAME) is used. A value of 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    aos_pool_t *p = NULL;
    aos_status_t *s = NULL;
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *headers = NULL;
    oss_request_options_t *options = NULL;
    aos_table_t *resp_headers = NULL;
    aos_list_t resp_body;
    aos_list_t buffer;
    aos_buf_t *content;
    char *buf = NULL;
    int64_t len = 0;
    int64_t size = 0;
    int64_t pos = 0;
    char b64_buf[1024];
    int b64_len;
    /* Use the JSON format. */
    /* (Optional) Set the Host value in the header of the callback request message, such as the Host value configured on your server. */
    char *callback =  "{"
        "\"callbackUrl\":\"http://oss-demo.aliyuncs.com:23450\","
         "\"callbackHost\":\"yourCallbackHost\","
        "\"callbackBody\":\"bucket=${bucket}&object=${object}&size=${size}&mimeType=${mimeType}\","
        "\"callbackBodyType\":\"application/x-www-form-urlencoded\""
        "}";
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Initialize parameters. */
    aos_pool_create(&p, NULL);
    options = oss_request_options_create(p);
    init_options(options);
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    aos_list_init(&resp_body);
    aos_list_init(&buffer);
    content = aos_buf_pack(options->pool, object_content, strlen(object_content));
    aos_list_add_tail(&content->node, &buffer);
    /* Add the callback to the header. */
    b64_len = aos_base64_encode((unsigned char*)callback, strlen(callback), b64_buf);
    b64_buf[b64_len] = '\0';
    headers = aos_table_make(p, 1);
    apr_table_set(headers, OSS_CALLBACK, b64_buf);
    /* Upload callback. */
    s = oss_do_put_object_from_buffer(options, &bucket, &object, &buffer,
        headers, NULL, NULL, &resp_headers, &resp_body);
    if (aos_status_is_ok(s)) {
        printf("put object from buffer succeeded\n");
    } else {
        printf("put object from buffer failed\n");
    }
    /* Get the buffer length. */
    len = aos_buf_list_len(&resp_body);
    buf = (char *)aos_pcalloc(p, (apr_size_t)(len + 1));
    buf[len] = '\0';
    /* Copy the buffer content to the memory. */
    aos_list_for_each_entry(aos_buf_t, content, &resp_body, node) {
        size = aos_buf_size(content);
        memcpy(buf + pos, content->pos, (size_t)size);
        pos += size;
    }
    /* Release the memory pool. This releases the memory allocated for various resources during the request. */
    aos_pool_destroy(p);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

CLI ossutil

Avant d'utiliser la commande put-object, assurez-vous d'avoir installé ossutil.

Exemples

  • Téléchargez un objet à partir d'une chaîne de caractères.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss"
  • Téléchargez un objet à partir d'un fichier local.

    ossutil api put-object --bucket examplebucket --key exampleobject --body file://uploadFile
  • Téléchargez une chaîne avec des métadonnées personnalisées.

    ossutil api put-object --bucket examplebucket --key exampleobject  --metadata user=aliyun --metadata email=ali***@aliyuncs.com --body "hi oss"
  • Téléchargez une chaîne avec des tags.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --tagging "TagA=A&TagB=B"
  • Téléchargez une chaîne en spécifiant une liste de contrôle d'accès (ACL) et une classe de stockage.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --object-acl private --storage-class IA
  • Téléchargez une chaîne avec un chiffrement côté serveur.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --server-side-encryption KMS --server-side-data-encryption SM4 --server-side-encryption-key-id 9468da86-3509-4f8d-a61e-6eab1eac****
  • Téléchargez une chaîne sans écraser un objet portant le même nom.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --forbid-overwrite true
  • Téléchargez une chaîne avec des paramètres de contrôle du cache.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --cache-control no-cache
  • Téléchargez une chaîne avec un nom de téléchargement personnalisé.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --content-disposition "attachment;filename=oss_download.jpg"

API associées

Les méthodes précédentes s'appuient sur des opérations API. Pour appeler directement les API RESTful, vous devez calculer manuellement la signature. PutObject.

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.

API

Action

Description

PutObject

oss:PutObject

Télécharge un objet.

oss:PutObjectTagging

Requis si vous spécifiez des tags d'objet à l'aide de l'en-tête x-oss-tagging lors du téléchargement d'un objet.

kms:GenerateDataKey

Requis si l'en-tête X-Oss-Server-Side-Encryption: KMS est défini sur KMS lors du téléchargement d'un objet.

kms:Decrypt

Facturation

Le téléchargement simple entraîne des frais pour les éléments facturables suivants. Tarification d'OSS.

API

Élément facturable

Description

PutObject

Requêtes PUT

Des frais de requête sont facturés en fonction du nombre de requêtes abouties.

Frais de stockage

Des frais de stockage sont facturés en fonction de la classe de stockage, de la taille et de la durée de stockage de l'objet.

FAQ

Téléchargement de fichiers volumineux

Le téléchargement simple prend en charge les fichiers jusqu'à 5 Go. Pour télécharger des fichiers supérieurs à 5 Go, utilisez le téléchargement en plusieurs parties.

Téléchargement de fichiers par lots

  • Utilisez la console OSS (prend en charge le filtrage manuel des fichiers)

    Cliquez sur le nom du bucket de destination. Cliquez sur Upload Object > Select Folders, sélectionnez le dossier à télécharger, supprimez les fichiers indésirables, puis cliquez sur Upload Object.

  • Utilisez ossbrowser (ne prend pas en charge le filtrage des fichiers)

    Cliquez sur le nom du bucket de destination. En haut de la page, cliquez sur Upload et sélectionnez le dossier à télécharger dans la liste déroulante.

  • Utilisez ossutil (prend en charge le filtrage par nom de fichier)

    Utilisez la commande ossutil cp avec l'option -r (--recursive) pour télécharger des fichiers par lots. Utilisez --include et --exclude pour filtrer par nom de fichier. cp (télécharger des fichiers).

    • Téléchargez des fichiers du dossier local localfolder vers le dossier desfolder du bucket examplebucket.

      ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/
    • Téléchargez par lots des fichiers répondant à des conditions spécifiques.

      Par exemple, la commande suivante télécharge tous les fichiers TXT.

      ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/ --include "*.txt"
  • Décompression de packages ZIP

    Utilisez la décompression ZIP pour télécharger des fichiers par lots : configurez les règles de décompression, téléchargez un fichier ZIP vers OSS, et Function Compute le décompresse automatiquement. Décompression de packages ZIP.

Accès temporaire pour des tiers

OSS propose deux méthodes pour l'accès temporaire par des tiers :

Traitement des fichiers téléchargés

  • Traitement d'images : compressez, appliquez un style ou analysez les images téléchargées. Traitement d'images.

  • ApsaraVideo Media Processing : traitez les fichiers multimédias téléchargés — reconnaissance de texte, extraction de sous-titres, transcodage et génération de vignettes. ApsaraVideo Media Processing.

Utilisation de noms de domaine personnalisés

Lors de l'utilisation d'un SDK, spécifiez un nom de domaine personnalisé lors de la création d'un OssClient. Définissez le paramètre cname sur true dans la configuration de chaque langage. Utiliser un nom de domaine personnalisé pour accéder à OSS.

Prévention des écrasements accidentels

Par défaut, un téléchargement simple écrase un objet portant le même nom. Utilisez l'une des méthodes suivantes pour prévenir les écrasements accidentels.

  • Activer le versioning

    Lorsque le versioning est activé, les objets écrasés sont enregistrés en tant que versions précédentes que vous pouvez restaurer à tout moment. Présentation du versioning.

  • Utilisez un paramètre de requête pour empêcher les écrasements

    Définissez l'en-tête x-oss-forbid-overwrite sur true dans la requête de téléchargement. Si un objet portant le même nom existe, le téléchargement échoue avec une erreur FileAlreadyExists. Si cet en-tête est omis ou défini sur false, l'objet existant est écrasé.

Réduction des frais de requêtes PUT

Si vous souhaitez télécharger un grand nombre d'objets, la spécification directe de la classe de stockage Deep Cold Archive pour les objets à télécharger entraîne des frais de requêtes PUT élevés. Nous vous recommandons de spécifier d'abord la classe de stockage Standard pour les objets lors de leur téléchargement, puis d'utiliser des règles de cycle de vie pour les convertir en classe de stockage Deep Cold Archive afin de réduire les frais de requêtes PUT.

Comportement du téléchargement simultané

Le résultat dépend de l'activation ou non du versioning :

image
  • Si le versioning est désactivé ou suspendu : si plusieurs utilisateurs téléchargent un objet portant le même nom, le dernier objet dont le téléchargement est terminé écrase le précédent. L'objet précédent n'est pas conservé. Par exemple, si l'utilisateur A termine son téléchargement après l'utilisateur B, l'objet téléchargé par l'utilisateur A est conservé.

  • Si le versioning est activé : le téléchargement d'un objet portant le même nom crée une nouvelle version, identifiée par un ID de version unique. OSS détermine la version actuelle en fonction de l'heure de début du téléchargement. Par exemple, si l'utilisateur B commence son téléchargement après l'utilisateur A, l'objet de l'utilisateur B devient la version actuelle.

Optimisation des performances de téléchargement

Le téléchargement de nombreux objets avec des préfixes séquentiels (horodatages, caractères alphabétiques) concentre les index dans une seule partition, ce qui réduit le débit de requêtes. Utilisez plutôt des préfixes aléatoires. Meilleures pratiques de performance OSS.