When you need to upload a file that does not exceed 5 GB to OSS and do not have high requirements for concurrent upload speeds, you can use simple upload.
Do not upload objects to the data storage directory OSS-HDFS service .dlsdata/
in a bucket for which OSS-HDFS service is enabled by using methods other than the OSS-HDFS service. Otherwise, the OSS-HDFS service may not function properly or data loss may occur.
Operations
Before you use simple upload, make sure that you have created a bucket.
Use the OSS console
In Alibaba Finance Cloud, OSS cannot be accessed over the Internet. Therefore, objects cannot be uploaded in the OSS console. If you want to upload objects, you must use OSS SDKs, ossutil, or ossbrowser.
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 navigation bar, select Object Management > Objects.
On the Objects page, click Upload Object.
In the Upload Object panel, select the files or directories that you want to upload.
Optional: Configure basic settings.
Basic Settings
Parameter
Description
Upload To
The directory in which an object is stored after the object is uploaded to the bucket.
Current Directory: Upload the object to the current directory.
Specified Directory: Upload the object to the specified directory. You must enter a directory name. If you enter a directory name that does not exist in the bucket, OSS automatically creates the directory.
The directory name must meet the following conventions:
The name must be 1 to 254 characters in length and can contain characters that are encoded in UTF-8.
The name cannot start with a forward slash (/) or a backslash (\).
The name cannot contain consecutive forward slashes (/).
The name cannot be
..
.
Object ACL
Specify the ACL of the objects.
Inherited From Bucket: The ACL of the bucket applies to the object.
Private (recommended): Only the object owner can read and write the object.
Public Read: Only the object owner can write the object. Other users, including anonymous users, can only read the object. This may result in unexpected access to the data in your bucket and unexpectedly high fees. Exercise caution when you set this parameter.
Public Read/Write: All users, including anonymous users, can read and write the object. This may result in data leaks and unexpectedly high fees. If a user uploads prohibited data or information, your legitimate interests and rights may be infringed. We recommend that you do not set the ACL to this value unless necessary.
For more information about object ACLs, see Object ACL.
Files to Upload
Select the files or directories that you want to upload.
You can click Select Files or Select Folders to select local files or folders, or drag and drop the target files or folders to the Files to Upload section.
If the folder that you want to upload contains files that you do not want to upload, click Remove to the right of the target file to remove the file from the list.
ImportantIf you upload an object that has the same name as an existing object in OSS to an unversioned bucket, the existing object is overwritten.
If you upload an object that has the same name as an existing object in OSS to a versioning-enabled bucket, the existing object becomes a previous version, and the uploaded object becomes the latest version.
Optional: Configure the storage class and encryption method.
Advanced
Parameter
Description
Storage Class
Specify the storage class of the objects.
Inherited From Bucket: The storage class of the bucket applies to the object.
Standard: Standard storage provides highly reliable, highly available, and high-performance object storage services that can support frequent data access. Standard storage is suitable for images that are used for social networking and sharing applications and storing data for audio and video applications, large websites, and big data analysis. Standard storage supports zone-redundant storage (ZRS) and locally redundant storage (LRS).
IA: IA storage provides highly durable object storage services at low costs. IA has a minimum billable size of 64 KB and a minimum billable storage duration of 30 days. You can access IA objects in real time. You are charged data retrieval fees when you access IA objects. IA storage is suitable for data that is infrequently accessed, such as once or twice a month. IA storage supports ZRS and LRS.
Archive: Archive storage provides highly durable object storage services at extremely low costs. Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 60 days. You can access an Archive object after it is restored or real-time access of Archive objects is enabled. The amount of time that is required to restore an Archive object is approximately 1 minute. You are charged data retrieval fees if you restore an Archive object. Direct access of Archive objects incurs Archive data retrieval fees based on the size of accessed Archive data. Archive is suitable for data that needs to be stored for a long period of time and is rarely accessed, such as archival data, medical images, scientific materials, and video footage. Archive storage supports ZRS and LRS.
Cold Archive: Cold Archive provides highly durable object storage services at lower costs than Archive storage. Cold Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 180 days. You must restore a Cold Archive object before you can access it. The amount of time that is required to restore a Cold Archive object varies based on the object size and the restore priority. You are charged data retrieval fees and API operation calling fees when you restore a Cold Archive object. Cold Archive is suitable for storing cold data over an ultra-long period of time. Such data includes data that must be retained for an extended period of time due to compliance requirements, raw data that is accumulated over an extended period of time in the big data and AI fields, retained media resources in the film and television industries, and archived videos from the online education industry. Cold Archive supports only LRS.
Deep Cold Archive: Deep Cold Archive provides highly durable object storage services at lower costs than Cold Archive storage. Deep Cold Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 180 days. You must restore a Deep Cold Archive object before you can access the object. The amount of time that is required to restore a Deep Cold Archive object varies based on the object size and restoration mode. You are charged data retrieval fees and API operation calling fees when you restore a Deep Cold Archive object. Deep Cold Archive is suitable for extremely cold data that must be stored for an extremely long period of time, including raw data that is accumulated over an extended period of time in the big data and AI fields, retained media resources, regulatory and compliance documents, and data that needs to be migrated from tapes to the cloud for long-term storage. Deep Cold Archive supports only LRS.
For more information, see Storage classes.
Encryption Method
Specify the server-side encryption method for the object.
Inherit From Bucket: The server-side encryption method of the bucket applies to the object.
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) managed by Key Management Service (KMS) to encrypt and decrypt objects. The Encryption Key parameter has the following options:
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-defined Metadata
Add descriptive information for the object. You can add multiple user metadata headers for an object. However, the total size of user metadata cannot exceed 8 KB. When you add user metadata, the parameter must start with
x-oss-meta-
and be assigned a value. Example: x-oss-meta-location:hangzhou.
Click Upload Object.
You can view the upload progress on the Upload Tasks tab.
Use ossbrowser
Before you use ossbrowser for simple upload, make sure that you have installed ossbrowser 2.0 and logged on to ossbrowser 2.0.
Click the name of the target bucket.
Click Upload and select the files or directories that you want to upload.
You can view the upload progress in the upper-right corner.
Use Alibaba Cloud SDKs
Upload a complete file
Upload a complete local file to a specified OSS bucket.
Java
Before you use OSS SDK for Java, make sure that you have configured credentials and installed OSS Java SDK.
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 use OSS SDK for Python, make sure that you have configured credentials and installed OSS Python SDK.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="put object from file sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Specify the --file_path parameter, which specifies the path of the local file to upload. This command line parameter is required.
parser.add_argument('--file_path', help='The path of Upload file.', required=True)
def main():
# Parse the command line parameters
args = parser.parse_args()
# Obtain access credentials from environment variables for authentication
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration to the one specified in the command line
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance
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, # Bucket name
key=args.key # Object name
),
args.file_path # Local file path
)
# Display the result information, including status code, request ID, MD5 hash, ETag, CRC-64 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")},'
)
# Script entry point, calls the main function when the file is run directly
if __name__ == "__main__":
main()
Go
Before you use OSS SDK for Go, make sure that you have configured credentials and installed OSS Go SDK.
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 strings
Upload string content from memory directly to OSS as a file.
Java
Before you use OSS SDK for Java, make sure that you have configured credentials and installed OSS Java SDK.
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 use OSS SDK for Python, make sure that you have configured credentials and installed OSS Python SDK.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="put object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse the command line parameters
# Obtain access credentials from environment variables for authentication
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration to the one specified in the command line
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance
client = oss.Client(cfg)
# Specify the string that you want to upload
text_string = "Hello, OSS!"
data = text_string.encode('utf-8') # Encode the string by using the UTF-8 encoding
# Execute the request to upload the object
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
))
# Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object 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() # Script entry point, calls the main function when the file is run directly
Go
Before you use OSS SDK for Go, make sure that you have configured credentials and installed OSS Go SDK.
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Specify the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®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
Upload a byte array from memory as file content, suitable for scenarios where binary data needs to be processed flexibly before uploading.
Python
Before you use OSS SDK for Python, make sure that you have configured credentials and installed OSS Python SDK.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="put object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse the command line parameters
# Obtain access credentials from environment variables for authentication
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration to the one specified in the command line
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance
client = oss.Client(cfg)
# Specify the data content that you want to upload
data = b'hello world'
# Execute the request to upload the object
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
))
# Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object 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() # Script entry point, calls the main function when the file is run directly
Go
Before you use OSS SDK for Go, make sure that you have configured credentials and installed OSS Go SDK.
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 file streams
Upload data by reading file streams from local files or memory.
Java
Before you use OSS SDK for Java, make sure that you have configured credentials and installed OSS Java SDK.
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 }
end
Upload network streams
Directly read data streams from the network and upload them to OSS, suitable for streaming data transfer needs without local storage.
Java
Before you use OSS SDK for Java, make sure that you have configured credentials and installed OSS Java SDK.
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 use OSS SDK for Python, make sure that you have configured credentials and installed OSS Python SDK.
import argparse
import requests
import alibabacloud_oss_v2 as oss
# Create a command line parameter parser
parser = argparse.ArgumentParser(description="put object sample")
# Specify the --region parameter, which specifies the region in which the bucket is located. This command line parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter, which specifies the endpoint that other services can use to access OSS. This command line parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
args = parser.parse_args() # Parse the command line parameters
# Obtain access credentials from environment variables for authentication
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configuration of the SDK and specify the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration to the one specified in the command line
cfg.region = args.region
# If the endpoint parameter is provided, specify the endpoint
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configurations to create an OSSClient instance
client = oss.Client(cfg)
# Send an HTTP GET request and obtain the response content
response = requests.get('http://www.aliyun.com')
# Execute the request to upload the object
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=response.content,
))
# Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object 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() # Script entry point, calls the main function when the file is run directly
Go
Before you use OSS SDK for Go, make sure that you have configured credentials and installed OSS Go SDK.
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
);
Upload progress bars
Display upload progress in real time during the upload process.
Java
Before you use OSS SDK for Java, make sure that you have configured credentials and installed OSS Java SDK.
For more information, see Java upload progress bars.
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 use OSS SDK for Go, make sure that you have configured credentials and installed OSS Go SDK.
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;
}
Upload callback
After a file is uploaded, notify the application server through a callback for subsequent processing. For more information about callback principles, see Callback.
Java
Before you use OSS SDK for Java, make sure that you have configured credentials and installed OSS Java SDK.
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 use OSS SDK for Python, make sure that you have configured credentials and installed OSS Python SDK.
import base64
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="put object sample")
# Add 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()
# Obtain access 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)
# Content to upload (string)
data = 'hello world'
# Construct callback parameters: specify the callback address and callback request body, using 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), using Base64 encoding
callback_var=base64.b64encode('{\"x:var1\":\"value1\",\"x:var2\":\"value2\"}'.encode()).decode(),
# Initiate the 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 return result (including status code, request ID, etc.)
print(vars(result))
if __name__ == "__main__":
main()
Go
Before you use OSS SDK for Go, make sure that you have configured credentials and installed OSS Go SDK.
package main
import (
"context"
"encoding/base64"
"encoding/json"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Specify the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®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}"
end
Browser.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 the command line tool ossutil
Before using put-object, 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://uploadFile
Upload 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 IA
Upload 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 true
Upload 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-cache
Upload 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 preceding operations are implemented based on API operations. If your program requires a high level of customization, you can directly call RESTful API operations. To directly call a RESTful API operation, you must include the signature calculation in your code. 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 Policy.
API | Action | Definition |
PutObject |
| Uploads an object. |
| When uploading an object, if you specify object tags through x-oss-tagging, this permission is required. | |
| When uploading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, these two permissions are required. | |
|
Billing
A simple upload of a local file to OSS incurs the fees described in the following table. 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 files larger than 5 GB?
Simple upload has a file size limit of 5 GB. For files larger than 5 GB, use multipart upload.
How do I batch upload files?
Use the OSS console (supports manual file filtering)
Click the target bucket name to access the bucket, click Upload Object > Scan Folder, select the folder to upload, remove unwanted files, and then click Upload Object.
Use ossbrowser (does not support file filtering)
Click the target bucket name to access the bucket, click the Upload button at the top of the page, and select Upload Folder from the dropdown list box.
Use the ossutil tool (supports filtering by filename)
Use the cp command of the ossutil tool with the -r (--recursive) option to batch upload files to OSS, and filter files by name using the --include and --exclude options. For more information, see cp (upload files).
Upload files in the localfolder directory to the desfolder directory in the examplebucket bucket.
ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/
Batch upload files that meet specific conditions.
Upload all files with the TXT format.
ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/ --include "*.txt"
ZIP package decompression
Configure decompression rules, compress multiple local files into a ZIP package, and then upload the ZIP package to OSS. Then, Function Compute is triggered to decompress the ZIP package and upload the decompressed files to OSS. For more information, see ZIP package decompression.
How do I share OSS resources with a third party for temporary access?
You can share OSS resources with a third party to grant them time-limited access by using two methods:
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, Use a signed URL to download an object.
Temporary access credentials from STS
If you want the third party to perform more OSS resource management operations beyond uploading and downloading, such as listing files and copying files, we recommend that you learn about and use temporary access credentials from STS. For more information, see Use STS to authorize temporary access to OSS.
How do I process files after uploading?
Image processing: Compress uploaded images, add custom styles, obtain image size information, and perform other operations. For more information, see Image processing.
Media processing: Perform text recognition, caption extraction, video transcoding, thumbnail generation, and other processing on uploaded images or videos. For more information, see ApsaraVideo Media Processing.
How do I use a custom domain name for simple upload?
When creating an OssClient using the SDK, use your custom domain name instead. For specific operations, refer to Step 3: Use a custom domain name in the SDK. Additionally, make sure that you enable CNAME resolution in your code.
How do I prevent files from being accidentally overwritten?
By default, OSS overwrites an existing object with an uploaded object that has the same name. You can use the following methods to prevent existing objects from being unexpectedly overwritten:
Enable versioning for the bucket
If you enable versioning for a bucket, objects that are overwritten in the bucket are saved as previous versions. You can recover the previous versions of the objects at any time. For more information, see Versioning overview.
Include the x-oss-forbid-overwrite parameter in the upload request
Include the x-oss-forbid-overwrite parameter in the header of the upload request and set its value to true. If an object with the same name already exists in OSS, the upload fails and a
FileAlreadyExists
error 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 PUT request costs?
If you want to upload a large number of objects and set the storage classes of the objects to Deep Cold Archive, you are charged high PUT request fees. We recommend that you set the storage classes of the objects to Standard when you upload the objects, and configure lifecycle rules to convert the storage classes of the Standard objects to Deep Cold Archive. This reduces PUT request fees.
How does OSS handle multiple users uploading files with the same name (including path)?
This depends on whether versioning is enabled:
When versioning is not enabled or suspended: If multiple users upload objects with the same name, the object that is uploaded last overwrites the previous one, and only the last uploaded object is retained. For example, if User A uploads an object after User B, the object from User A is retained and replaces the object from User B.
When 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 identifies the latest version of an object based on the upload start time. For example, if User A and User B upload objects with identical name to a versioning-enabled bucket, and User B begins the upload after User A, the object uploaded by User B will be designated as the latest version.
How do I optimize upload performance?
If you upload many objects and the names of the objects contain sequential prefixes such as timestamps and letters, multiple object indexes may be stored in a single partition. As a result, latency increases when many requests are sent to query these objects. We recommend that you use random prefixes instead of sequential prefixes to specify object names when you upload many objects. For more information, see OSS performance best practices.