Use simple upload to upload a file that is 5 GB or smaller to Object Storage Service (OSS) if you do not require high concurrent upload speeds.
Do not upload objects to the .dlsdata/ data storage directory in a bucket for which the OSS-HDFS service is enabled using methods other than the OSS-HDFS service. Otherwise, the OSS-HDFS service may not function properly or data loss may occur.
Procedures
Before you use simple upload, make sure that you have created a bucket.
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.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation pane, choose Object Management > Objects.
On the Objects page, click Upload Object.
In the Upload Object panel, select the files or folders that you want to upload.
Optional: Configure basic options.
Basic Options
Parameter
Description
Upload To
Set the storage path for the file after it is uploaded to the destination bucket.
Current Directory: Upload the file to the current folder.
Specified Directory: Upload the file to a specified folder. You must enter a folder name. If the folder that you enter does not exist, OSS automatically creates the folder and uploads the file to it.
The folder name must meet the following requirements:
The name must be 1 to 254 characters in length and can contain only UTF-8 characters.
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 access control list (ACL) for the file.
Inherited from Bucket: The ACL of the file is the same as the ACL of the bucket.
Private (Recommended): Only the file owner has read and write permissions on the file. Other users cannot access the file.
Public Read: The file owner has read and write permissions. Other users, including anonymous users, can only read the file. 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 file. This may cause data leaks and increased fees. If malicious users upload illegal information, your legal rights may be infringed. Do not select this option unless necessary.
For more information about file ACLs, see Object ACL.
Files to Upload
Select the files or folders that you want 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.
If a folder contains files that you do not want to upload, click Remove to the right of the file to remove it from the list.
ImportantIf you upload a file with the same name as an existing file to a bucket for which versioning is disabled, the existing file is overwritten.
If you upload a file with the same name as an existing file to a bucket for which versioning is enabled, the uploaded file becomes the current version and the existing file becomes a previous version.
Optional: Set advanced options, such as file storage class and encryption method.
Advanced Options
Parameter
Description
Storage Class
Set the storage class for the file.
Inherited from Bucket: The storage class of the file is the same as 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 social and sharing applications, large websites, and big data analytics. The Standard storage class supports zone-redundant storage (ZRS) and locally redundant storage (LRS).
IA: Provides highly durable object storage at a lower 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. Data retrieval fees are generated when you access data. 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: 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. Data retrieval fees are generated for restored data, and real-time access of Archive objects fees are generated for directly accessed data. 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 it can be accessed. The restoration time depends on the data size and the selected restoration mode. Data retrieval fees and request fees are generated for restoration. 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 only supports 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 it can be accessed. The restoration time depends on the data size and the selected restoration mode. Data retrieval fees and request fees are generated for restoration. 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 only supports LRS.
For more information, see Storage classes.
Encryption Method
Set the server-side encryption method for the file.
Inherited from Bucket: The server-side encryption method of the file 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 a customer master key (CMK) that is managed by Key Management Service (KMS) or a specified CMK ID to encrypt and decrypt data. The following describes the CMK parameter that corresponds to KMS:
alias/acs/oss(CMK ID): The default CMK is used to encrypt objects and automatically decrypt objects when they are downloaded.
alias/<cmkname>(CMK ID): A custom CMK is used to encrypt objects in the bucket. The CMK ID is recorded in the metadata of the encrypted objects. Objects are automatically 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 Metadata
Adds descriptive information to an object. You can add multiple user-defined metadata entries. The total size of all user-defined metadata cannot exceed 8 KB. When you add user-defined metadata, the parameter must start with the
x-oss-meta-prefix and be assigned a value, for example, x-oss-meta-location:hangzhou.
Click Upload Object.
You can then view the file upload progress on the Upload Tasks tab.
Use ossbrowser
Before you use ossbrowser for simple upload, make sure that you have installed and logged on to ossbrowser 2.0.
Click the name of the destination bucket.
Click Upload and select the files or folders that you want to upload.
You can view the upload progress in the upper-right corner.
Use Alibaba Cloud SDKs
Upload a complete file
You can upload a complete local file to a specified OSS bucket.
Java
Before you start, make sure 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 start, make sure that you have configured credentials and installed 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 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 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 configured information.
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) value, 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 start, make sure that you have configured credentials and installed 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(®ion, "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({
// 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
<?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 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
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++
#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
#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
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')Upload a string
You can upload string content from memory directly to OSS as a file.
Java
Before you start, make sure 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.*;
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, make sure that you have configured credentials and installed 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 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 configured information.
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.
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
))
# Print the status code, request ID, Content-MD5, ETag, CRC64 value, 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 that you have configured credentials and installed OSS SDK for Go.
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Specify the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "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
You can upload a byte array from memory as file content. This method is suitable for scenarios where binary data needs to be processed before it is uploaded.
Python
Before you start, make sure that you have configured credentials and installed 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 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 configured information.
client = oss.Client(cfg)
# Define the data to upload.
data = b'hello world'
# Execute the request to upload the object. Specify the bucket name, object name, and data.
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
))
# Print the status code, request ID, Content-MD5, ETag, CRC64 value, 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 that you have configured credentials and installed 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(®ion, "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 name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt.
// Do not include the bucket name in the full path of the object.
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) {
// 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());
}Upload a file stream
You can read data from a local file or memory and upload the data using a file input stream.
Java
Before you start, make sure 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.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 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. Example: examplebucket.
bucket: 'examplebucket',
});
async function putStream () {
try {
// Use chunked encoding. When you call putStream, OSS SDK initiates an HTTP PUT request for chunked encoding.
// Specify the full path of the local file. Data stream is read from the local file.
// 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.
let stream = fs.createReadStream('D:\\localpath\\examplefile.txt');
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
let result = await client.putStream('exampledir/exampleobject.txt', stream);
// Do not use chunked encoding. If contentLength is specified in options, chunked encoding is not used.
// let stream = fs.createReadStream('D:\\localpath\\examplefile.txt');
// let size = fs.statSync('D:\\localpath\\examplefile.txt').size;
// let result = await client.putStream(
// You can set stream to specify the types of Readable Stream, such as file stream and 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(
# 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')
# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt.
bucket.put_object('exampleobject.txt') do |stream|
100.times { |i| stream << i.to_s }
endUpload a network stream
You can directly read a data stream from the network and upload it to OSS. This method is suitable for streaming data transfer that does not require local storage.
Java
Before you start, make sure 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.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, make sure that 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 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 configured information.
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.
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 value, 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 that 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(®ion, "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 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. Example: examplebucket.
bucket: 'examplebucket',
});
// Specify the network stream URL.
const url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20220908/cbgh/IMG_example.jpg";
// Import the duplex stream.
// You can set stream to specify the types of Readable Stream, such as file stream and network stream.
const Duplex = require("stream").Duplex;
// Instantiate the duplex stream.
let stream = new Duplex();
urllib.request(url, (err, data, res) => {
if (!err) {
// Receive data from the duplex stream.
stream.push(data);
stream.push(null);
client
// Specify the full path of the object. Example: example.png. Do not include the bucket name in the full path.
.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
);
Show an upload progress bar
You can display the upload progress in real time during the upload process.
Java
Before you start, make sure that you have configured access credentials and installed OSS SDK for Java V1.
For more information, see 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 start, make sure 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(®ion, "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 specifies the size of the data that is uploaded by the callback function.
// transferred specifies the size of the uploaded data.
// total specifies the total size of the object that you want to upload.
std::cout << "ProgressCallback[" << userData << "] => " <<
increment <<" ," << transfered << "," << total << std::endl;
}
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);
/* 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 object. */
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;
}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;
}Use an upload callback
After a file is uploaded, the application server is notified through a callback for subsequent processing. For more information about how callbacks work, see Callback.
Java
Before you start, make sure that you have configured access credentials and installed OSS SDK for Java V1.
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.ByteArrayInputStream;
public class Demo {
public static void main(String[] args) throws Exception{
// Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
String objectName = "exampledir/exampleobject.txt";
// Specify the address of the server to which the callback request is sent. Example: https://example.com:23450.
String callbackUrl = "yourCallbackServerUrl";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
String content = "Hello OSS";
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,new ByteArrayInputStream(content.getBytes()));
// Configure upload callback parameters.
Callback callback = new Callback();
callback.setCallbackUrl(callbackUrl);
// (Optional) Specify the CallbackHost field in the callback request header.
// callback.setCallbackHost("yourCallbackHost");
// Set the callback request body in JSON format and define placeholder variables within.
callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object},\\\"mimeType\\\":${mimeType},\\\"size\\\":${size},\\\"my_var1\\\":${x:var1},\\\"my_var2\\\":${x:var2}}");
// Configure custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:.
callback.addCallbackVar("x:var1", "value1");
callback.addCallbackVar("x:var2", "value2");
putObjectRequest.setCallback(callback);
// Perform the upload operation.
PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
// Read the message content returned from the upload callback.
byte[] buffer = new byte[1024];
putObjectResult.getResponse().getContent().read(buffer);
// You must close the obtained stream after the data is read. Otherwise, connection leaks may occur. Consequently, no connections are available and an exception occurs.
putObjectResult.getResponse().getContent().close();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}Python
Before you start, make sure that you have configured credentials and installed OSS SDK for Python.
import base64
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="put object sample")
# Add 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 (string).
data = 'hello world'
# Construct the callback parameter (callback): Specify the webhook address and the request body for the callback. 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 custom variables (callback-var). Use Base64 encoding.
callback_var=base64.b64encode('{\"x:var1\":\"value1\",\"x:var2\":\"value2\"}'.encode()).decode(),
# Initiate an upload request with 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 SDK for Go.
package main
import (
"context"
"encoding/base64"
"encoding/json"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Specify the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "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 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. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the file is uploaded from the local path of the project to which the sample program belongs.
var localFilename = "D:\\localpath\\examplefile.txt";
// Specify the URL of the callback server. Example: https://example.com:23450.
const string callbackUrl = "yourCallbackServerUrl";
// Specify the callbackBody field included in the callback request.
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 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 string endpoint = "https://oss-cn-hangzhou.aliyuncs.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.
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
{
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 an 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 response to the upload callback request.
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");
varpath = require("path");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "yourregion",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "examplebucket",
});
const options = {
callback: {
// Specify the address of the callback server that receives the callback request. Example: http://oss-demo.aliyuncs.com:23450.
url: "http://oss-demo.aliyuncs.com:23450",
// (Optional) Specify the Host field included in the callback request header.
//host: 'yourCallbackHost',
// Specify the body of the callback request.
body: "bucket=${bucket}&object=${object}&var1=${x:var1}&var2=${x:var2}",
// Specify Content-Type in the callback request.
contentType: "application/x-www-form-urlencoded",
// Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
callbackSNI: true,
// Configure custom parameters for the callback request.
customValue: {
var1: "value1",
var2: "value2",
},
},
};
async function put() {
try {
// Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object.
// By default, if you do not specify the path of the local file, the file is uploaded from the local path of the project to which the sample program belongs.
let result = await client.put(
"exampleobject.txt",
path.normalize("/localpath/examplefile.txt"),
options
);
console.log(result);
} catch (e) {
console.log(e);
}
}
put();
Ruby
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# 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')
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}"
endBrowser.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id="submit">Upload Callbacks</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({
// 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 Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret.
accessKeyId: "yourAccessKeyId",
accessKeySecret: "yourAccessKeySecret",
// Specify the security token obtained from STS.
stsToken: "yourSecurityToken",
// Specify the name of the bucket. Example: examplebucket.
bucket: "examplebucket",
});
const options = {
callback: {
// Specify the public endpoint of the server that receives the callback request.
url: "http://examplebucket.aliyuncs.com:23450",
// Specify the Host field included in the callback request header.
// host: 'yourHost',
// Specify the body field included in the callback request.
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}",
// Specify the Content-Type field in the callback request.
// contentType: 'application/x-www-form-urlencoded',
// Specify whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
callbackSNI: true,
// Configure the custom parameters for the callback request.
customValue: {
var1: "value1",
var2: "value2",
},
},
};
// Query DOM.
const submit = document.getElementById("submit");
// Implement the upload callback.
submit.addEventListener("click", () => {
client
.put("example.txt", new Blob(["Hello World"]), options)
.then((r) => console.log(r));
});
</script>
</body>
</html>
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");
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");
// Obtain the returned callback information. You can obtain the callback information only if you specify servercallback in the request.
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 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";
/* Specify the URL of the callback server. */
std::string ServerName = "https://example.aliyundoc.com:23450";
/* 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);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "Thank you for using Aliyun Object Storage Service!";
/* Configure 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 resources such as 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;
}Use ossutil
Before you use the put-object command, make sure that you have installed ossutil.
Examples
Upload an object by uploading a string.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss"Upload an object by uploading a local file.
ossutil api put-object --bucket examplebucket --key exampleobject --body file://uploadFileUpload an object by uploading a string and specify the metadata of the object.
ossutil api put-object --bucket examplebucket --key exampleobject --metadata user=aliyun --metadata email=ali***@aliyuncs.com --body "hi oss"Upload an object by uploading 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 by uploading 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 IAUpload an object by uploading a string and specify the method that is used to encrypt 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 by uploading a string and prevent the object that you want to upload from overwriting existing objects that have the same name.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --forbid-overwrite trueUpload an object by uploading a string and specify the caching behavior of the web page when the object is downloaded.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --cache-control no-cacheUpload an object by uploading a string and specify the name of the object when the object is downloaded.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --content-disposition "attachment;filename=oss_download.jpg"
Related API operations
The procedures described above are based on API operations. If your application has high customization requirements, you can directly make RESTful API requests. To do this, you must manually write code to calculate the signature. For more information, see 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 Policy or Bucket policies.
API | Action | Definition |
PutObject |
| Uploads an object. |
| When uploading an object, if you specify object tags through | |
| When uploading an object, if the object metadata contains | |
|
Billing
Uploading files to OSS using simple upload incurs the following billable items. For more information about pricing, see 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
How do I upload a file larger than 5 GB?
Simple upload supports files up to 5 GB. To upload files larger than 5 GB, you must use multipart upload.
How do I upload files in batches?
Use the OSS console (supports manual file filtering)
Click the name of the destination bucket to open it. Click Upload File > Scan Folders. Select the folder that you want to upload, remove any unwanted files, and then click Upload File.
Use ossbrowser (does not support file filtering)
Click the name of the destination bucket to open it. Click the Upload button at the top of the page and select the folder that you want to upload from the drop-down list.
Use the ossutil tool (supports filtering by filename)
You can use the cp command of the ossutil tool with the -r (--recursive) option to upload files to OSS in batches. You can also use the --include and --exclude options to filter files by name. For more information, see cp (upload files).
This command uploads files from the on-premises folder `localfolder` to the `desfolder` folder in the `examplebucket` bucket.
ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/You can also upload files that meet specific conditions in batches.
For example, the following command uploads all files in the TXT format.
ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/ --include "*.txt"
Decompress a ZIP package
You can use the ZIP package decompression feature. First, configure decompression rules. Then, package multiple files into a ZIP file and upload it to OSS. This triggers Function Compute to decompress the package and upload the decompressed files back to OSS, which implements a batch upload. For more information, see Upload and automatically decompress a ZIP package.
How do I share OSS resources with third parties for temporary access?
OSS provides two methods to grant third parties temporary access:
Signed URL
If you only need a third party to temporarily upload or download specific files, a signed URL can meet your needs. For detailed instructions, see Use a signed URL to upload an object and Use a signed URL to download an object.
Temporary access credentials from Security Token Service (STS)
If you want a third party to perform more OSS resource management operations than just uploading and downloading, such as listing and copying files, you can use temporary access credentials from STS. For more information, see Use STS temporary access credentials to access OSS.
How do I process uploaded files?
Image processing: You can perform operations on uploaded images, such as compression, adding custom styles, and obtaining image size information. For more information, see Image processing.
Media processing: You can perform operations on uploaded images or videos, such as text recognition, caption extraction, video transcoding, and thumbnail generation. For more information, see ApsaraVideo Media Processing.
How do I use a custom domain name for simple upload?
When you create an OssClient using an SDK, use a custom domain name. For more information, see the SDK examples in Use a custom domain name to access OSS. Note that the cname parameter must be set to true in the configurations for all languages.
How do I prevent a file from being accidentally overwritten?
By default, simple upload overwrites an object that has the same name. You can use one of the following methods to prevent an object from being accidentally overwritten.
Enable versioning
After you enable versioning, an overwritten object is saved as a previous version. You can restore the previous version of the object at any time. For more information, see Versioning overview.
Include a parameter in the upload request to prevent overwriting an object that has the same name
In the header of the upload request, include the x-oss-forbid-overwrite parameter and set its value to true. If an object with the same name as the one you are uploading already exists in OSS, the upload fails and a
FileAlreadyExistserror is returned. If this parameter is not included or its value is set to false, the object with the same name is overwritten.
How do I reduce costs for PUT requests?
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.
If multiple users upload a file with the same name and path, which version does OSS retain?
The result depends on whether versioning is enabled:
If versioning is disabled or suspended: If multiple users upload an object with the same name, the object that is last uploaded overwrites the previous ones. Only the last uploaded object is retained. For example, if User A finishes uploading after User B, the object uploaded by User A is retained.
If versioning is enabled: Each time an object with the same name is uploaded, a new version is created and identified by a 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 uploaded by User B is marked as the current version.
How do I optimize upload performance?
If you upload many objects using sequential prefixes such as timestamps or letters in object names, many object indexes might be stored in a specific partition of the bucket. This can decrease the request rate. We recommend that you use random prefixes instead of sequential prefixes in object names when you upload many objects. For more information, see OSS performance best practices.