All Products
Search
Document Center

Object Storage Service:Simple upload

Last Updated:May 26, 2026

Use simple upload to upload objects up to 5 GB to OSS when high concurrency is not required.

Warning

In a bucket where the OSS-HDFS service is enabled, do not upload objects to the data storage directory .dlsdata/ using any method other than the OSS-HDFS service itself. Doing so may cause the service to malfunction or result in data loss.

Upload methods

Before you start, create a bucket.

Important

Due to a policy change to improve compliance and security, starting March 20, 2025, new OSS users must use a custom domain name (CNAME) to perform data API operations on OSS buckets located in Chinese mainland regions. Default public endpoints are restricted for these operations. Refer to the official announcement for a complete list of the affected operations. If you access your data via HTTPS, you must bind a valid SSL Certificate to your custom domain. This is mandatory for OSS Console access, as the console enforces HTTPS.

OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation pane, choose Object Management > Objects.

  4. On the Objects page, click Upload Object.

  5. In the Upload Object panel, select the files or folders that you want to upload.

    1. Optional: Configure basic options.

      Basic options

      Parameter

      Description

      Upload to

      Set the destination path in the bucket.

      • Current Directory: Upload the objects to the current directory.

      • Specified Directory: Upload to a specified directory. You must enter a directory name. If the directory does not exist, OSS creates it automatically.

        The directory name must meet the following requirements:

        • The name must be 1 to 254 characters in length and use UTF-8 encoding.

        • The name cannot start with a forward slash (/) or a backslash (\).

        • The name cannot contain consecutive forward slashes (/).

        • The name cannot be ...

      Object ACL

      Set the object ACL.

      • Inherited from Bucket: The object inherits the ACL of the bucket.

      • Private (Recommended): Only the object owner has read and write permissions for the object.

      • Public Read: The object owner has read and write permissions, while other users, including anonymous users, have read-only access. This may cause data leaks and increased fees. Use this option with caution.

      • Public Read/Write: All users, including anonymous users, can read and write the object. This may cause data leaks and increased fees. If malicious users upload illegal information, you may be held legally liable. Do not select this option unless necessary.

      Object ACL.

      Files to Upload

      Select files or folders to upload.

      Click Select Files or Select Folders to select local files or folders. You can also drag the target files or folders to the upload area.

      To exclude a file from upload, click Remove next to it.

      Important
      • If you upload an object with the same name as an existing object into a bucket where versioning is disabled, the upload overwrites the existing object.

      • If you upload an object with the same name as an existing object to a bucket for which versioning is enabled, the uploaded object becomes the current version and the existing object becomes a previous version.

    2. Optional: Configure advanced options, such as storage class and server-side encryption method.

      Advanced options

      Parameter

      Description

      Storage Class

      Set the storage class.

      • Inherited from Bucket: The object inherits the storage class of the bucket.

      • Standard: Provides a highly reliable, available, and performant object storage service that supports frequent data access. It is suitable for various use cases, such as social and sharing applications, large websites, and big data analytics. The Standard storage class supports zone-redundant storage (ZRS) and locally redundant storage (LRS).

      • Infrequent Access: Provides highly durable object storage at a low storage cost. It has a minimum billable size of 64 KB and a minimum storage duration of 30 days. It supports real-time data access. Accessing data incurs retrieval fees. This storage class is suitable for business scenarios with low access frequency, such as one to two times per month on average. The Infrequent Access storage class supports ZRS and LRS.

      • Archive Storage: Provides highly durable object storage at an extremely low storage cost. It has a minimum billable size of 64 KB and a minimum storage duration of 60 days. Archive Storage data can be accessed after it is restored, which takes about one minute, or accessed directly. Restored data incurs retrieval fees, while directly accessed data incurs real-time access fees. Archive Storage is suitable for long-term data retention, such as for archives, medical images, scientific data, and video footage. The Archive Storage class supports ZRS and LRS.

      • Cold Archive: Provides highly durable object storage at a lower cost than Archive Storage. It has a minimum billable size of 64 KB and a minimum storage duration of 180 days. Data must be restored before access. The restoration time depends on the data size and the selected restoration mode. Restoration incurs data retrieval and request fees. This storage class is suitable for cold data that requires very long-term storage, such as data retained for compliance, raw data accumulated in big data and artificial intelligence (AI) fields, media assets in the film and television industry, and archived videos in the online education industry. The Cold Archive storage class supports only LRS.

      • Deep Cold Archive: Provides highly durable object storage at a lower cost than Cold Archive. It has a minimum billable size of 64 KB and a minimum storage duration of 180 days. Data must be restored before access. The restoration time depends on the data size and the selected restoration mode. Restoration incurs data retrieval and request fees. This storage class is suitable for extremely cold data that requires ultra-long-term storage, such as long-term retention of raw data in big data and AI fields, long-term retention of media data, regulatory and compliance archives, and tape replacement. The Deep Cold Archive storage class supports only LRS.

      Overview of storage classes.

      Encryption Method

      Set the server-side encryption method.

      • Inherited from Bucket: The object inherits the server-side encryption method of the bucket.

      • OSS-Managed: Objects are encrypted with keys managed by OSS. OSS uses a unique key for each object, and for added security, these data keys are also encrypted with a master key.

      • KMS: Use a default customer master key (CMK) managed by KMS or a specified CMK ID to encrypt and decrypt data. The following describes the CMK parameter:

        • alias/acs/oss(CMK ID): OSS uses the default service key to encrypt data in the bucket and automatically decrypts objects when you download them.

        • alias/<cmkname>(CMK ID): OSS encrypts data in the bucket with the specified CMK and records its ID in the object's metadata. OSS then automatically decrypts the object for users with the necessary permissions. <cmkname> is the optional alias that you configure when you create the key.

          Before using the specified CMK ID, you need to create a common key or external key in the same region as the Bucket in the KMS console. For detailed operations, see Create a CMK

      • Encryption Algorithm: Only AES256 is supported.

      User-defined Metadata

      Add custom metadata to an object. Total size of all entries must not exceed 8 KB. Each key must start with the x-oss-meta- prefix and be assigned a value, for example, x-oss-meta-location:hangzhou.

  6. Click Upload Object.

    You can then view the object upload progress on the Upload Tasks tab.

Ossbrowser

Before you use ossbrowser for simple upload, install ossbrowser 2.0 and log in to ossbrowser 2.0.

  1. Click the name of the destination bucket.

  2. Click Upload, and select the files or folders to upload.

    You can view the upload progress in the upper-right corner.

Alibaba Cloud SDKs

Upload a complete file

Upload a local file to a specified bucket.

Java

Before you begin, ensure that you have configured access credentials and installed OSS SDK for 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

Before you begin, ensure that you have configured credentials and installed the OSS SDK for 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

Before you begin, ensure that you have configured credentials and installed the OSS SDK for 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 OSSClient instance.
const client = new Client({
  // Specify the AccessKey ID obtained from Security Token Service (STS).
  accessKeyId: 'yourAccessKeyId',
  // Specify the AccessKey secret obtained from STS.
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the security token obtained from STS.
  securityToken: 'yourSecurityToken',
  // 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: 'oss-cn-hangzhou',
});

const bucket = 'yourBucketName'; // Specify the name of the bucket.

const key='yourObjectName '; // Specify the name of the object.

const putObject = async () => {
  try {
    // Use the putObject method to upload data to object in the specified bucket and pass parameters.
    const res = await client.putObject({
      bucket, // Specify the name of the bucket.
      key, // Specify the name of the object.
      data: 'hello world' // The data that you want to upload. In this example, a simple string is uploaded.
    });

    // Display the result of the object upload operation.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Capture exceptions during the request.
    if (err instanceof RequestError) {
      // If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC.
      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 {
      // Display other unknown types of errors.
      console.log('unknown error: ', err);
    }
  }
}

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

Android

// Construct 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 object 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 control list (ACL) 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 objects with the same name from being overwritten.
// 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");
// Specify 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.
// 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) {
    // A client exception occurred, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // A server exception occurred.
    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')

Upload a string

Upload string content from memory as an object.

Java

Before you start, ensure you have configured access credentials and installed OSS SDK for 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

Before you start, ensure you have configured credentials and installed OSS Python SDK.

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

Before you start, ensure you have configured credentials and installed OSS Go SDK.

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);
}

Upload a byte array

Upload binary data from a byte array. Useful when you need to process data before uploading.

Python

Before you start, make sure you have configured credentials and installed the OSS SDK for 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

Before you start, make sure you have configured credentials and installed the OSS SDK for 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);

// Construct 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) {
    // A client exception occurred, such as a network exception.
    e.printStackTrace();
} catch (ServiceException e) {
    // A server exception occurred.
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

Upload a file stream

Read data from a local file or memory and upload it using a file stream.

Java

Before you start, ensure you have configured access credentials and installed OSS SDK for 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

Upload a network stream

Stream data from a network source directly to OSS without saving it locally.

Java

Before you start, ensure you have configured access credentials and installed OSS SDK for 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

Before you start, ensure you have configured credentials and installed OSS SDK for 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

Before you start, ensure you have configured credentials and installed OSS SDK for 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
);

Upload progress bar

Track the upload progress in real time.

Java

Before you begin, ensure that you have configured access credentials and installed OSS SDK for Java V1.

Java upload progress bar.

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

Before you begin, ensure that you have configured credentials and installed OSS SDK for 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

// Construct an upload request. 
// Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /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");

// Configure 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 specifies the size of the uploaded part of the object. Unit: bytes. 
        // totalSize specifies the total size of the object that you want to upload. Unit: bytes. 
        Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
    }
});

// Aasynchronously upload the local file. 
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) {
        // Handle request exceptions. 
        if (clientExcepion != null) {
            // Handle client exceptions, such as network exceptions. 
            clientExcepion.printStackTrace();
        }
        if (serviceException != null) {
            // Handle service exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
// task.cancel(); // You can cancel the download task. 
// task.waitUntilFinished(); // Wait until the task is 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"
/* 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. */
const char *endpoint = "yourEndpoint";

/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the full path of the local file. */
const char *local_filename = "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 char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* 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. */    
    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"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure 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 in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the 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 the object with the specified progress bar displayed. */
    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 operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Upload callback

After upload, use a callback to notify your application server for further processing. Callback.

Java

Before you start, make sure that you have configured access credentials and installed OSS Java SDK 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

Before you start, make sure that you have configured credentials and installed OSS Python SDK.

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

Before you start, make sure that you have configured credentials and installed OSS Go SDK.

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({
  // Replace 'yourregion' with 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",
});

const options = {
  callback: {
    // Set the URL of the server that receives callback requests. For example, http://oss-demo.aliyuncs.com:23450.
    url: "http://oss-demo.aliyuncs.com:23450",
    // (Optional) Set the Host header for the callback request. This is the Host value configured on your server.
    //host: 'yourCallbackHost',
    // Set the value of the request body for the callback.
    body: "bucket=${bucket}&object=${object}&var1=${x:var1}&var2=${x:var2}",
    // Set 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 that is specified by callbackUrl when the client initiates a callback request.
    callbackSNI: true,
    // Set custom parameters for the callback request.
    customValue: {
      var1: "value1",
      var2: "value2",
    },
  },
};

async function put() {
  try {
    // Specify the full path of the object and the full path of the local file. The full path of the object cannot contain the bucket name.
    // If a local path is not specified, the file is uploaded from the default local path of the project.
    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"
/* 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. */
const char *endpoint = "yourEndpoint";

/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content = "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 char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* 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. */    
    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"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure 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;
    /* Specify the callback parameters in the JSON format. */
    /* (Optional) Specify the Host field included in the callback request header. */
    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 in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Initialize the 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);
    /* Configure the 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");
    }
    /* Obtain 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 content in the buffer 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 operation releases the memory resources allocated for the request. */
    aos_pool_destroy(p);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

ossutil CLI

Before you use the put-object command, ensure you have installed ossutil.

Examples

  • Upload an object from a string.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss"
  • Upload an object from a local file.

    ossutil api put-object --bucket examplebucket --key exampleobject --body file://uploadFile
  • Upload an object from a string and add custom metadata.

    ossutil api put-object --bucket examplebucket --key exampleobject  --metadata user=aliyun --metadata email=ali***@aliyuncs.com --body "hi oss"
  • Upload an object from a string and specify tags for the object.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --tagging "TagA=A&TagB=B"
  • Upload an object from a string and specify the ACL and storage class of the object.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --object-acl private --storage-class IA
  • Upload an object from a string and specify the server-side encryption method for the object.

    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****
  • Upload an object from a string and prevent the object from overwriting an existing object that has the same name.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --forbid-overwrite true
  • Upload an object from a string and specify the object's caching behavior.

    ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --cache-control no-cache
  • Upload an object from a string and specify the name of the object when it is downloaded.

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

Related APIs

The preceding methods are built on API operations. To call the RESTful APIs directly, you must manually calculate the signature. PutObject.

Permissions

By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.

API

Action

Description

PutObject

oss:PutObject

Uploads an object.

oss:PutObjectTagging

Required if you specify object tags by using the x-oss-tagging header when you upload an object.

kms:GenerateDataKey

Required if the X-Oss-Server-Side-Encryption: KMS header is set to KMS when you upload an object.

kms:Decrypt

Billing

Simple upload incurs charges for the following billable items. OSS Pricing.

API

Billable item

Description

PutObject

PUT requests

You are charged request fees based on the number of successful requests.

Storage fees

You are charged storage fees based on the storage class, size, and storage duration of the object.

FAQ

Upload large files

Simple upload supports files up to 5 GB. To upload files larger than 5 GB, use multipart upload.

Upload files in batches

  • Use the OSS console (supports manual file filtering)

    Click the name of the destination bucket. Click Upload Object > Select Folders, select the folder to upload, remove any unwanted files, and then click Upload Object.

  • Use ossbrowser (does not support file filtering)

    Click the name of the destination bucket. At the top of the page, click Upload and select the folder to upload from the drop-down list.

  • Use ossutil (supports filtering by filename)

    Use the ossutil cp command with the -r (--recursive) option to batch upload files. Use --include and --exclude to filter by filename. cp (upload files).

    • Upload files from the local folder localfolder to the desfolder folder in the examplebucket bucket.

      ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/
    • Upload files that meet specific conditions in batches.

      For example, the following command uploads all TXT files.

      ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/ --include "*.txt"
  • ZIP package decompression

    Use ZIP decompression to upload files in batches: configure decompression rules, upload a ZIP file to OSS, and Function Compute decompresses it automatically. Upload and automatically decompress a ZIP package.

Temporary access for third parties

OSS provides two methods for temporary third-party access:

Process uploaded files

  • Image processing: Compress, style, or analyze uploaded images. Image processing.

  • ApsaraVideo Media Processing: Process uploaded media files — text recognition, subtitle extraction, transcoding, and thumbnail generation. ApsaraVideo Media Processing.

Use custom domain names

When using an SDK, specify a custom domain name when creating an OssClient. Set the cname parameter to true in each language's configuration. Use a custom domain name to access OSS.

Prevent accidental overwrites

By default, a simple upload overwrites an object with the same name. Use one of the following methods to prevent accidental overwrites.

  • Enable versioning

    With versioning enabled, overwritten objects are saved as previous versions that you can restore at any time. Versioning overview.

  • Use a request parameter to prevent overwrites

    Set the x-oss-forbid-overwrite header to true in the upload request. If an object with the same name exists, the upload fails with a FileAlreadyExists error. If omitted or set to false, the existing object is overwritten.

Reduce PUT request fees

Setting the storage class to Deep Cold Archive during upload incurs higher PUT request fees. We recommend that you set the storage classes of the objects to Standard when you upload the objects, and configure lifecycle rules to convert the storage classes of the Standard objects to Deep Cold Archive. This reduces PUT request fees.

Concurrent upload behavior

The result depends on whether versioning is enabled:

image
  • If versioning is disabled or suspended: If multiple users upload an object with the same name, the last object to finish uploading overwrites the previous one. The previous object is not retained. For example, if User A finishes uploading after User B, the object uploaded by User A is retained.

  • If versioning is enabled: Uploading an object with the same name creates a new version, identified by a unique version ID. OSS determines the current version based on the upload start time. For example, if User B starts uploading after User A, the object from User B becomes the current version.

Optimize upload performance

Uploading many objects with sequential prefixes (timestamps, alphabetical characters) concentrates indexes in a single partition, reducing the request rate. Use random prefixes instead. OSS performance best practices.