All Products
Search
Document Center

Object Storage Service:Upload files, images, and videos to OSS

Last Updated:Mar 27, 2025

For local files, images, or videos no larger than 5 GB that don't require high concurrent upload performance, the simple upload method is suitable.

Prerequisites

Ensure you have created a bucket. For more information, see Create a bucket.

Operation methods

Warning

Avoid uploading objects to the data storage directory .dlsdata/ in a bucket with OSS-HDFS service enabled through non-OSS-HDFS methods to prevent disruption of the OSS-HDFS service or data loss.

Use the OSS console

Note

In Alibaba Finance Cloud, the OSS console is not accessible over the Internet. Use SDKs, ossutil, or ossbrowser for object uploads.

  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. Select Object Management > Objects from the left-side navigation pane.

  4. On the Objects page, click Upload Object.

  5. In the Upload Object panel, set the parameters as described below.

    1. Configure basic options.

      Parameter

      Description

      Upload To

      Specify the directory in which an object is stored after the object is uploaded to the bucket.

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

      • Specified Directory: Upload the object to the specified directory. You need to enter the directory name. If the directory whose name you entered does not exist, OSS automatically creates the directory and uploads the object to the directory.

        The directory name must meet the following requirements:

        • The name can contain only UTF-8 characters. The name must be 1 to 254 characters in length.

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

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

        • The name cannot be .. .

      File ACL

      Specify the ACL of the object.

      • Inherit Bucket: The ACL of the object is the same as that of the bucket.

      • Private (recommended): Only the owner of the object has read and write permissions on the object. Other users do not have permissions to access the object.

      • Public Read: The owner of the object has read and write permissions on the object. Other users (including anonymous users) can only read the object. This may result in unauthorized access to the data in your bucket and high fees. Proceed with caution.

      • Public Read/Write: All users (including anonymous users) can read and write the object. This may result in unauthorized access to the data in your bucket and high fees. If a user uploads prohibited data or information, your legal rights may be infringed. We recommend that you do not set the ACL to public-read-write unless necessary.

      For more information about the ACL of the object, see Set the ACL of the object.

      Files to Upload

      Select the files or directories that you want to upload.

      You can click Select Files or Select Folders to select local files or directories, or directly drag the target files or directories to the area of files to upload.

      If the directory to upload contains files that you do not want to upload, click Remove on the right side of the target file to remove it from the file list.

      Important
      • If you upload a local file to an unversioned bucket and the local file has the same name as an existing object in the bucket, the uploaded object overwrites the existing object.

      • If you upload a local file to a versioned bucket and the local file has the same name as an existing object in the bucket, the uploaded object becomes the latest version, and the existing object becomes a previous version.

    2. Optional:Set advanced options such as the object's storage class and encryption method.

      Parameter

      Description

      Storage Class

      Specify the storage class of the object.

      • Inherit Bucket: The storage class of the object is the same as that of the bucket.

      • Standard: Provides highly reliable, highly available, and high-performance object storage services that support frequent data access. Standard storage is suitable for various scenarios, such as social networking applications, image, audio, and video sharing applications, large-scale websites, and big data analytics. Standard storage supports zone-redundant storage (ZRS) and locally redundant storage (LRS).

      • Infrequent Access: Provides highly durable object storage services at a lower storage cost. IA has a minimum billable size of 64 KB and a minimum billable storage duration of 30 days. You can access IA objects in real time. However, you are charged data retrieval fees when you access IA objects. IA storage is suitable for data that is infrequently accessed, such as once or twice a month. IA storage supports zone-redundant storage and locally redundant storage.

      • Archive Storage: Provides highly durable object storage services at an extremely low storage cost. Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 60 days. You can access an Archive object after it is restored or real-time access of Archive objects is enabled. You are charged Archive data retrieval fees based on the size of accessed Archive data. Archive is suitable for data that needs to be stored for a long period of time and is rarely accessed, such as archival data, medical images, scientific materials, and video footage. Archive storage supports zone-redundant storage and locally redundant storage.

      • Cold Archive: Provides highly durable object storage services at a lower storage cost than Archive storage. Cold Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 180 days. You must restore a Cold Archive object before you can access it. The amount of time that is required to restore a Cold Archive object varies based on the object size and the restore priority. You are charged data retrieval fees and API operation calling fees when you restore a Cold Archive object. Cold Archive is suitable for cold data that must be stored for an extremely long period of time, such as data that is retained for compliance purposes, raw data that is accumulated over an extended period of time in the big data and AI fields, retained media resources, and archived videos in the online education industry. Cold Archive supports only locally redundant storage.

      • Deep Cold Archive: Provides highly durable object storage services at a lower storage cost than Cold Archive storage. Deep Cold Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 180 days. You must restore a Deep Cold Archive object before you can access it. The amount of time that is required to restore a Deep Cold Archive object varies based on the object size and the restore priority. You are charged data retrieval fees and API operation calling fees when you restore a Deep Cold Archive object. Deep Cold Archive is suitable for extremely cold data that must be stored for an extremely long period of time, including raw data that is accumulated over an extended period of time in the big data and AI fields, retained media resources, regulatory and compliance documents, and data that needs to be migrated from tapes to the cloud for long-term storage. Deep Cold Archive supports only locally redundant storage.

      For more information, see Introduction to storage classes.

      Encryption Method

      Specify the server-side encryption method for the object.

      • Inherit Bucket: The server-side encryption method of the object is the same as that of the bucket.

      • OSS-Managed: The keys managed by OSS are used to encrypt objects in the bucket. OSS encrypts each object by using a different key. OSS also uses master keys to encrypt the keys.

      • KMS: Use the default customer master key (CMK) or a specified CMK ID to encrypt and decrypt the object. The following section describes the Encryption Key that is used by KMS:

        • alias/acs/oss(CMK ID): The default CMK managed by KMS is used to generate keys for encryption and decryption.

        • alias/<cmkname>(CMK ID): A custom CMK is used to generate keys for object encryption. The CMK ID is recorded in the metadata of the encrypted objects. Objects are decrypted when they are downloaded by users who have the decryption permissions. <cmkname> is the optional name of the CMK that you configured when you created the CMK.

          Before you specify a CMK ID, you must create a normal key or an external key in the same region in which the bucket is located in the KMS console. For more information, see Create a CMK.

      • Encryption Algorithm: Only AES256 is supported.

      User-defined Metadata

      Add descriptive information for the object. You can add multiple user metadata headers for an object. However, the total size of user metadata cannot exceed 8 KB. When you add user metadata, you must use x-oss-meta- as the prefix of the parameter and specify a value for the parameter. Example: x-oss-meta-location:hangzhou.

    3. Click Upload Object.

      The upload progress for each file is displayed on the Upload Tasks tab.

Use the graphical management tool ossbrowser

ossbrowser supports the same bucket-level operations as the OSS console. Follow the on-screen instructions in ossbrowser for simple uploads. For details on using ossbrowser, see Quickly use ossbrowser.

Use Alibaba Cloud SDKs

Java

The following example demonstrates file upload using the Java SDK. For sample code for simple upload scenarios like uploading strings, file streams, and network streams, see Java simple upload.

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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. 
        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

The following example demonstrates file upload using the Python SDK. For sample code for simple upload scenarios like uploading strings and network streams, see Python simple upload.

# -*- coding: utf-8 -*-
import oss2
import os
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 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. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# 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. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# The file must be opened in binary mode. 
# Specify the full path of the local file. 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. 
with open('D:\\localpath\\examplefile.txt', 'rb') as fileobj:
    # Use the seek method to read data from byte 1,000 of the file. The data is uploaded from byte 1000 to the last byte of the local file. 
    fileobj.seek(1000, os.SEEK_SET)
    # Use the tell method to obtain the current position. 
    current = fileobj.tell()
    # Specify the full path of the object. Do not include the bucket name in the full path. 
    bucket.put_object('exampleobject.txt', fileobj)

Go

The following example demonstrates file upload using the Go SDK. For sample code for simple upload scenarios like uploading strings, file streams, and network streams, see Go simple upload.

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

The following example demonstrates file upload using the Node.js SDK. For sample code for simple upload scenarios like uploading strings, file streams, and network streams, see Upload strings and Streaming upload.

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

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that 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 the bucket. 
  bucket: 'examplebucket',
});

// Add custom request headers.
const headers = {
  // Specify the storage class of the object. 
  'x-oss-storage-class': 'Standard',
  // Specify the access control list (ACL) of the object. 
  'x-oss-object-acl': 'private',
  // When you access an object by using the URL of the object, specify that the object is downloaded as an attachment. In this example, the name of the downloaded object is example.jpg. 
  'Content-Disposition': 'attachment; filename="example.txt"',
  // Specify tags for the object. You can specify multiple tags for the object at the same time. 
  'x-oss-tagging': 'Tag1=1&Tag2=2',
  // Specify whether the PutObject operation overwrites an object that has the same name. In this example, the x-oss-forbid-overwrite parameter is set to true, which specifies that an existing object that has the same name cannot be overwritten by the uploaded object. 
  'x-oss-forbid-overwrite': 'true',
};

async function put () {
  try {
    // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. 
    // 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. 
    const result = await client.put('exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt')
    // Specify custom headers.
    ,{headers}
    );
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

PHP

The following code snippet illustrates how to upload a file using the PHP SDK. For more examples of simple upload scenarios, such as uploading strings, refer to PHP simple upload.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

// 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. 
$provider = new EnvironmentVariableCredentialsProvider();
// 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. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the file is uploaded from the path of the project to which the sample program belongs. 
$filePath = "D:\\localpath\\examplefile.txt";

try{
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->uploadFile($bucket, $object, $filePath);
} catch(OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . "OK" . "\n");

Browser.js

For details on the Browser.js SDK, see Browser.js simple upload.

<!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

The following example demonstrates how to upload a file using the .NET SDK. For more information on simple upload scenarios, such as uploading strings, refer to .NET simple upload.

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

Android

The following code snippet provides an example of file upload using the Android SDK. For more examples of simple upload scenarios, such as uploading binary byte[] arrays, see Android simple upload.

// 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");

// (Optional) Specify the object metadata. 
 ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("application/octet-stream"); // Set content-type. 
// metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // Specify the MD5 hash that is used for MD5 verification. 
// Set the 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");
// Specify that the uploaded object that has the same name as an existing object does not overwrite the existing object. 
// metadata.setHeader("x-oss-forbid-overwrite", "true");
// Specify one or more tags for the object. 
// metadata.setHeader("x-oss-tagging", "a:1");
// Specify the server-side encryption algorithm that is used to encrypt the object when OSS creates the object. 
// metadata.setHeader("x-oss-server-side-encryption", "AES256");
// Specify the CMK that is managed by KMS. This parameter takes effect 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) {
    // Handle client-side exceptions, such as network errors. 
    e.printStackTrace();
} catch (ServiceException e) {
    // Handle server-side exceptions. 
    Log.e("RequestId", e.getRequestId());
    Log.e("ErrorCode", e.getErrorCode());
    Log.e("HostId", e.getHostId());
    Log.e("RawMessage", e.getRawMessage());
}

iOS

For more information on the iOS SDK, see iOS simple upload.

OSSPutObjectRequest * put = [OSSPutObjectRequest new];

// Specify the name of the bucket. Example: examplebucket. 
put.bucketName = @"examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
put.objectKey = @"exampledir/exampleobject.txt";
put.uploadingFileURL = [NSURL fileURLWithPath:@"<filePath>"];
// put.uploadingData = <NSData *>; // Directly upload NSData. 

// (Optional) Configure an upload progress indicator. 
put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
    // Specify the number of bytes that are being uploaded, the number of bytes that are uploaded, and the total number of bytes that you want to upload. 
    NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
// Configure optional fields. 
// put.contentType = @"application/octet-stream";
// Specify Content-MD5. 
// put.contentMd5 = @"eB5eJF1ptWaXm4bijSPyxw==";
// Specify the method that is used to encode the object. 
// put.contentEncoding = @"identity";
// Specify the method that is used to display the object content. 
// put.contentDisposition = @"attachment";
// Configure object metadata or HTTP headers. 
// NSMutableDictionary *meta = [NSMutableDictionary dictionary];
// Specify the object metadata. 
// [meta setObject:@"value" forKey:@"x-oss-meta-name1"];
// Set the access control list (ACL) 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"];
// Specify that this upload overwrites an existing object that has the same name. 
// [meta setObject:@"true" forKey:@"x-oss-forbid-overwrite"];
// Specify one or more tags for the object. 
// [meta setObject:@"a:1" forKey:@"x-oss-tagging"];
// Specify the server-side encryption algorithm that is used to encrypt the destination object when Object Storage Service (OSS) creates the object. 
// [meta setObject:@"AES256" forKey:@"x-oss-server-side-encryption"];
// Specify the customer master key (CMK) that is managed by Key Management Service (KMS). This parameter takes effect only if you set x-oss-server-side-encryption 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 execution of the current thread but does not block the task progress. 
// [putTask waitUntilFinished];
// [put cancel];

C++

The following example demonstrates how to upload a file using the C++ SDK. For more examples of simple upload scenarios, such as uploading strings, see C++ simple upload.

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

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* 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. */
    std::string Endpoint = "yourEndpoint";
    /* 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. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* 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. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
    /* Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. In this example, localpath indicates the local path in which 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) Set the ACL to private and the storage class to Standard for the object. */
    //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 exceptions. */
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

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

C

The following example demonstrates how to upload a file using the C SDK. For more examples of simple upload scenarios, such as uploading strings, see C simple upload.

#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[])
{
    /* 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_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 object. */
    resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, &buffer, headers, &resp_headers);
    /* Check whether the object is uploaded. */
    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 operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Ruby

The following example demonstrates how to upload a file using the Ruby SDK. For more examples of simple upload scenarios, such as streaming upload, see Ruby streaming upload.

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  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. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Upload the object. 
bucket.put_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')

Use the command-line tool ossutil

The command-line tool ossutil can be used for file uploads. For instructions on installing ossutil, see Install ossutil.

Use the following command to upload a local file to the bucket .

ossutil api put-object --bucket examplebucket --key exampleobject --body file://uploadFile

For more details on this command, see put-object.

Related operations

The operations described above are based on API calls. For a higher degree of customization, you can directly invoke RESTful APIs. When making a direct API call, you must incorporate signature computation into your code. For more information, see PutObject.

Permissions

By default, an Alibaba Cloud account has full permissions on resources in the account. In contrast, RAM users and RAM roles associated with an Alibaba Cloud account initially have no permissions. To manage resources by using a RAM user or role, you must grant the required permissions via RAM policies or Bucket policies.

API

Action

Description

PutObject

oss:PutObject

Grants the permission to upload objects.

oss:PutObjectTagging

Specifies the tags of the object by using the x-oss-tagging header when you upload objects.

kms:GenerateDataKey

When uploading an object, if the object's metadata includes X-Oss-Server-Side-Encryption: KMS, permissions for both operations are required.

kms:Decrypt

Billing description

When you upload a file to OSS using the simple upload method, you incur charges for several items. For details on the pricing of these items, please refer to 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.

Learn more

Manage the upload process

  • Monitor the Upload Progress: To monitor the upload progress and display a progress bar, see Upload Progress Bar.

  • Upload Callback: You can set up a callback request to an application server after a file is uploaded. For more information, see Callback.

Process files after upload

  • Image Processing: You can compress uploaded images, apply custom styles, and retrieve size information. For more information, see Image Processing.

  • Media Processing: Perform tasks such as optical character recognition (OCR), caption extraction, video transcoding, and thumbnail generation on uploaded media. For more information, see Media Processing.

Access OSS data in ECI

Use OSS as the storage backend for batch jobs like Hadoop and Spark, and access OSS data directly in ECI. For more information, see Access OSS Data in ECI.

Upload files by using a client

Client-side uploads can improve speed, reduce server load, and avoid transit compared to server-side proxy uploads. For faster file uploads to OSS, client-side uploading is recommended. For more information, see Client-Side Upload.

FAQ

How to upload files larger than 5 GB

The simple upload method has a file size limit of 5 GB. For files exceeding this limit, you should use multipart upload.

How to perform batch uploads?

The OSS console and ossbrowser facilitate batch uploads from a specified directory, though file filtering is not supported. For file filtering capabilities, ossutil is the recommended tool.

  • Use the OSS console

    Navigate to the desired bucket by clicking its name, then click Upload File > Scan Folder. Select the folder you want to upload and click Upload File.

  • Use ossbrowser

    In the bucket interface, click the Upload button at the top of the page and choose Upload folder from the drop-down list box.

  • Use the ossutil tool

    To batch upload files to OSS, utilize the cp command with the -r (--recursive) option in ossutil. For detailed instructions, see cp (upload files).

    • To upload files from the localfolder directory to the desfolder directory in the examplebucket bucket:

      ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/
    • You can batch upload files that satisfy specific conditions.

      Upload all files in TXT format.

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

    Leverage the ZIP package decompression feature by first setting up decompression rules. Compress multiple files into a ZIP package, upload it to OSS, and trigger Function Compute to decompress the ZIP package, uploading the files to OSS. For more details, refer to ZIP package decompression.

How to share OSS resources for temporary access by third parties?

OSS offers two methods for granting temporary third-party access:

How to use a custom domain name for simple upload?

Create an OssClient with an SDK using a custom domain name. For more information, refer to Step 3: Use a custom domain name. Ensure the cname parameter is set to true in the configuration for each language.

How to prevent files from being accidentally overwritten?

By default, OSS overwrites an existing object with a newly uploaded object of the same name. To avoid unintended overwrites, consider the following options:

  • Enable versioning

    Activating versioning for a bucket preserves overwritten objects as previous versions, which can be restored at any time. For more details, see Introduction to versioning.

  • Use the x-oss-forbid-overwrite parameter

    Include the x-oss-forbid-overwrite parameter in the upload request header and set it to true. This prevents the upload of an object with the same name as an existing one, returning a FileAlreadyExists error. Without this parameter or if set to false, the existing object will be overwritten.

How to reduce PUT request fees?

If you want to upload a large number of objects and set the storage classes of the objects to Deep Cold Archive, you are charged high 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.

How does OSS retain files with the same name (including the path) that are uploaded by multiple users?

Retention of identically named files uploaded by different users depends on whether versioning is enabled:

image
  • When versioning is disabled or suspended: The last uploaded object with the same name overwrites any previous ones, resulting in only the most recent upload being retained. For instance, if User A uploads an object after User B, User A's object will be the one kept.

  • When versioning is enabled: Each upload of an object with the same name generates a new version, identified by a unique version ID. OSS determines the latest version of an object based on the start time of the upload. For example, if User A starts uploading before User B, but User B's upload finishes last, User B's object will be considered the latest version.

How to optimize upload performance?

Uploading numerous objects with sequential prefixes, such as timestamps or letters, may cause multiple object indexes to be stored in a single partition, leading to increased latency. To enhance performance, it is advisable to use random prefixes for object names when uploading large quantities of objects. For optimization techniques, see OSS performance best practices.