You can use simple upload to upload files up to 5 GB to Object Storage Service (OSS). This method is suitable for scenarios that do not require high concurrent upload speeds.
In a bucket where the OSS-HDFS service is enabled, do not use services other than OSS-HDFS to upload objects to the .dlsdata/ data storage directory. This can affect the normal operation of the OSS-HDFS service or cause data loss.
Methods
Before you use simple upload, make sure that you have created a bucket.
Use the OSS console
OSS in Alibaba Finance Cloud does not have public endpoints. You cannot upload files from the console. Instead, you can use an SDK, 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 navigation pane on the left, choose Object Management > Objects.
On the Objects page, click Upload Object.
In the Upload Object panel, select the files or folders that you want to upload.
Optional: Configure basic options.
Basic Options
Parameter
Description
Upload To
Set the storage path for the file after it is uploaded to the destination bucket.
Current Directory: Upload the file to the current folder.
Specified Directory: Upload the file to a specified folder. You must enter a folder name. If the specified folder does not exist, OSS automatically creates it and uploads the file to it.
The following folder naming conventions apply:
Use UTF-8 characters. The name must be 1 to 254 characters in length.
The name cannot start with a forward slash (/) or a backslash (\).
The name cannot contain consecutive forward slashes (/).
The name cannot be
...
File ACL
Set the access control list (ACL) for the object.
Inherit From Bucket: The object ACL is the same as the bucket ACL.
Private (Recommended): Only the object owner has read and write permissions on the object. Other users cannot access the object.
Public Read: The object owner has read and write permissions on the object. Other users, including anonymous users, can read the object. This may cause data leaks and unexpectedly high fees. Exercise caution when you select this option.
Public Read/Write: All users, including anonymous users, can read and write to the object. This may cause data leaks and unexpectedly high fees. If malicious users write illegal information to the object, your legitimate rights and interests may be infringed. We do not recommend that you grant public read/write permissions unless necessary.
For more information about object ACLs, see Object ACL.
Files to Upload
Select the files or folders that you want to upload.
You can click Select Files or Select Folders to select local files or folders. You can also drag the destination files or folders to the upload area.
If a folder contains files that you do not want to upload, click Remove to the right of the file to remove it from the file list.
ImportantIf you upload a file to a bucket for which versioning is disabled, the existing file with the same name is overwritten.
If you upload a file to a bucket for which versioning is enabled, the uploaded file becomes the current version and the existing file becomes a previous version.
Optional: Configure advanced options such as the storage class and encryption method for the files.
Advanced Options
Parameter
Description
Storage Class
Set the storage class for the file.
Inherit From Bucket: The file uses the same storage class as the bucket.
Standard: Provides highly reliable, highly available, and high-performance object storage services that support frequent data access. This storage class is suitable for a variety of use cases, such as social networking, sharing of images and videos, large websites, and big data analytics. Standard supports zone-redundant storage (ZRS) and locally redundant storage (LRS).
Infrequent Access: Provides a highly durable object storage service with lower storage costs. This storage class has a minimum billable size of 64 KB and a minimum storage period of 30 days. It supports real-time data access but incurs data retrieval fees. It is suitable for business scenarios with low access frequency, such as once or twice a month on average. Infrequent Access (IA) supports ZRS and LRS.
Archive: Provides a highly durable object storage service with very low storage costs. This storage class has a minimum billable size of 64 KB and a minimum storage period of 60 days. Archive objects can be accessed after they are restored (which takes about 1 minute) or accessed in real time. Data retrieval fees are incurred for restored objects, and real-time access fees are incurred for objects that are accessed in real time. Archive is suitable for business scenarios that require long-term data retention, such as for archival data, medical images, scientific materials, and video footage. Archive supports ZRS and LRS.
Cold Archive: Provides a highly durable object storage service with lower storage costs than Archive. This storage class has a minimum billable size of 64 KB and a minimum storage period of 180 days. Data can be accessed only after it is restored. The restoration time depends on the data size and the selected restoration mode. Data retrieval fees and request fees are incurred for data restoration. Cold Archive is suitable for business scenarios that require long-term storage of cold data, such as data that must be retained for compliance purposes, raw data accumulated in the big data and artificial intelligence (AI) fields, media resources retained for a long time in the film and television industry, and archived videos in the online education industry. Cold Archive supports only LRS.
Deep Cold Archive: Provides a highly durable object storage service with lower storage costs than Cold Archive. This storage class has a minimum billable size of 64 KB and a minimum storage period of 180 days. Data can be accessed only after it is restored. The restoration time depends on the data size and the selected restoration mode. Data retrieval fees and request fees are incurred for data restoration. Deep Cold Archive is suitable for business scenarios that require ultra-long-term storage of extremely cold data, such as long-term retention of raw data in the big data and AI fields, long-term retention of media data, regulatory and compliance archives, and tape replacement. Deep Cold Archive supports only LRS.
For more information, see Storage classes.
Encryption Method
Set the server-side encryption method for the file.
Inherit From Bucket: The file uses the same server-side encryption method as the bucket.
OSS-Managed: The keys managed by OSS are used to encrypt objects in the bucket. OSS encrypts each object by using a different key. OSS also uses master keys to encrypt the keys.
SSE-KMS: Uses the default customer master key (CMK) managed by KMS or a specified CMK ID for encryption and decryption. The Encryption Key for KMS is described as follows:
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
Adds descriptive information to an object. You can add multiple pieces of user-defined metadata, but their total size cannot exceed 8 KB. When you add user-defined metadata, the parameter must start with the
x-oss-meta-prefix and be assigned a value. For example, x-oss-meta-location:hangzhou.
Click Upload Object.
You can view the upload progress on the Upload Tasks tab.
Use the ossbrowser graphical user interface
Before you use ossbrowser for a simple upload, make sure that you have installed ossbrowser 2.0 and logged on to ossbrowser 2.0.
Click the name of the destination bucket.
Click Upload and select the files or folders that you want to upload.
You can then view the upload progress in the upper-right corner.
Use Alibaba Cloud SDKs
Upload a complete file
You can directly upload a complete local file to a specified OSS bucket.
Java
Before you begin, make sure that you have configured access credentials and installed the OSS SDK for Java V1.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.File; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. // By default, if the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. String filePath= "D:\\localpath\\examplefile.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Create a PutObjectRequest object. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath)); // The following sample code provides an example on how to specify the storage class and ACL of an object when you upload the object: // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // Upload the local file. PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }Python
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Python.
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 begin, make sure that you have configured credentials and installed the OSS SDK for Go.
package main import ( "context" "flag" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Specify the global variables. var ( region string // The region in which the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // Specify the init function used to initialize command line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command line parameters. flag.Parse() // Check whether the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check whether the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check whether the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSSClient instance. client := oss.NewClient(cfg) // Specify the path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt. localFile := "/Users/localpath/exampleobject.txt" // Create a request to upload the local file. putRequest := &oss.PutObjectRequest{ Bucket: oss.Ptr(bucketName), // Specify the name of the bucket. Key: oss.Ptr(objectName), // Specify the name of the object. StorageClass: oss.StorageClassStandard, // Set the storage class of the object to Standard. Acl: oss.ObjectACLPrivate, // Set the access control list (ACL) of the object to private. Metadata: map[string]string{ "yourMetadataKey 1": "yourMetadataValue 1", // Specify the metadata of the object. }, } // Execute the request to upload the local file. result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile) if err != nil { log.Fatalf("failed to put object from file %v", err) } // Display the result of the object upload operation. log.Printf("put object from file result:%#v\n", result) } Node.js
const OSS = require('ali-oss') const path=require("path") const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: 'yourregion', // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, authorizationV4: true, // Specify the name of the bucket. bucket: 'examplebucket', }); // Add custom request headers. const headers = { // Specify the storage class of the object. 'x-oss-storage-class': 'Standard', // Specify the access control list (ACL) of the object. 'x-oss-object-acl': 'private', // When you access an object by using the URL of the object, specify that the object is downloaded as an attachment. In this example, the name of the downloaded object is example.jpg. 'Content-Disposition': 'attachment; filename="example.txt"', // Specify tags for the object. You can specify multiple tags for the object at the same time. 'x-oss-tagging': 'Tag1=1&Tag2=2', // Specify whether the PutObject operation overwrites an object that has the same name. In this example, the x-oss-forbid-overwrite parameter is set to true, which specifies that an existing object that has the same name cannot be overwritten by the uploaded object. 'x-oss-forbid-overwrite': 'true', }; async function put () { try { // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. // If the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. const result = await client.put('exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt') // Specify custom headers. ,{headers} ); console.log(result); } catch (e) { console.log(e); } } put();PHP
<?php // Introduce autoload files to load dependent libraries. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Specify descriptions for command line parameters. $optsdesc = [ "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object. "file" => ['help' => 'Local path to the file you want to upload.', 'required' => True], // (Required) Specify the path of the local file. ]; // Convert the parameter descriptions to a long options list required by getopt. // Add a colon (:) to the end of each parameter to indicate that a value is required. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Parse the command line parameters. $options = getopt("", $longopts); // Check whether the required parameters are configured. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain the help information about the parameters. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // If the required parameters are not configured, exit the program. } } // Obtain values from the parsed parameters. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. $key = $options["key"]; // The name of the object. $file = $options["file"]; // The path of the local file. // Obtain access credentials from environment variables. // Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configurations of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided. } // Create an OSSClient instance. $client = new Oss\Client($cfg); // Check whether the local file exists. if (!file_exists($file)) { echo "Error: The specified file does not exist." . PHP_EOL; // If the local file does not exist, an error message is displayed and the program is exited. exit(1); } // Open the local file and prepare for the simple upload task. // Use fopen to open the local file in read-only mode and convert the file to a stream by using Utils::streamFor. $body = Oss\Utils::streamFor(fopen($file, 'r')); // Create a PutObjectRequest object to upload the local file. $request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key); $request->body = $body; // Specify that the HTTP request body is a file stream. // Execute the simple upload request. $result = $client->putObject($request); // Display the result of the simple upload request. // Display the HTTP status code, the request ID, and the ETag of the object to check whether the request is successful. printf( 'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful. 'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request. 'etag:' . $result->etag . PHP_EOL // The ETag of the object, which is used to identify the content of the object. ); Browser.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <input id="file" type="file" /> <button id="upload">Upload an Object</button> <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script> <script> const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: "yourRegion", authorizationV4: true // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. accessKeyId: "yourAccessKeyId", accessKeySecret: "yourAccessKeySecret", // Specify the security token that you obtained from STS. stsToken: "yourSecurityToken", // Specify the name of the bucket. bucket: "examplebucket", }); // Select the local file from the drop-down list. Example: <input type="file" id="file" />. let data; // Create and specify the Blob data. //const data = new Blob(['Hello OSS']); // Create an OSS buffer and specify the content of the OSS buffer. //const data = new OSS.Buffer(['Hello OSS']); const upload = document.getElementById("upload"); async function putObject(data) { try { // Specify the full path of the object. Do not include the bucket name in the full path. // Specify the object name or the full path of the object to upload data to the current bucket or a specific directory in the bucket. For example, set the object name to exampleobject.txt or the path of the object to exampledir/exampleobject.txt. // You can set the data to files, Blob data, or OSS buffers. const options = { meta: { temp: "demo" }, mime: "json", headers: { "Content-Type": "text/plain" }, }; const result = await client.put("examplefile.txt", data, options); console.log(result); } catch (e) { console.log(e); } } upload.addEventListener("click", () => { const data = file.files[0]; putObject(data); }); </script> </body> </html> .NET
using Aliyun.OSS; using Aliyun.OSS.Common; // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. var endpoint = "yourEndpoint"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the name of the bucket. Example: examplebucket. var bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. var objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. var localFilename = "D:\\localpath\\examplefile.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters based on your requirements. var conf = new ClientConfiguration(); // Use the signature algorithm V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { // Upload the local file. client.PutObject(bucketName, objectName, localFilename); Console.WriteLine("Put object succeeded"); } catch (Exception ex) { Console.WriteLine("Put object failed, {0}", ex.Message); }Harmony
import Client, { RequestError } from '@aliyun/oss'; // Create an OSSClient instance. const client = new Client({ // Specify the AccessKey ID obtained from Security Token Service (STS). accessKeyId: 'yourAccessKeyId', // Specify the AccessKey secret obtained from STS. accessKeySecret: 'yourAccessKeySecret', // Specify the security token obtained from STS. securityToken: 'yourSecurityToken', // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: 'oss-cn-hangzhou', }); const bucket = 'yourBucketName'; // Specify the name of the bucket. const key='yourObjectName '; // Specify the name of the object. const putObject = async () => { try { // Use the putObject method to upload data to object in the specified bucket and pass parameters. const res = await client.putObject({ bucket, // Specify the name of the bucket. key, // Specify the name of the object. data: 'hello world' // The data that you want to upload. In this example, a simple string is uploaded. }); // Display the result of the object upload operation. console.log(JSON.stringify(res)); } catch (err) { // Capture exceptions during the request. if (err instanceof RequestError) { // If known types of errors exist, display information, such as the error code, error message, request ID, HTTP status code, and EC. console.log('code: ', err.code); console.log('message: ', err.message); console.log('requestId: ', err.requestId); console.log('status: ', err.status); console.log('ec: ', err.ec); } else { // Display other unknown types of errors. console.log('unknown error: ', err); } } } // Call the putObject function to perform the object upload operation. putObject();Android
// Construct an upload request. // Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /storage/emulated/0/oss/examplefile.txt. // Do not include the bucket name in the full path of the object. PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt"); // (Optional) Specify the object metadata. ObjectMetadata metadata = new ObjectMetadata(); // metadata.setContentType("application/octet-stream"); // Set content-type. // metadata.setContentMD5(BinaryUtil.calculateBase64Md5(uploadFilePath)); // Specify the MD5 hash that is used for MD5 verification. // Set the ACL of the object to private. metadata.setHeader("x-oss-object-acl", "private"); // Set the storage class of the object to Standard. metadata.setHeader("x-oss-storage-class", "Standard"); // Specify that the uploaded object that has the same name as an existing object does not overwrite the existing object. // metadata.setHeader("x-oss-forbid-overwrite", "true"); // Specify one or more tags for the object. // metadata.setHeader("x-oss-tagging", "a:1"); // Specify the server-side encryption algorithm that is used to encrypt the object when OSS creates the object. // metadata.setHeader("x-oss-server-side-encryption", "AES256"); // Specify the CMK that is managed by KMS. This parameter takes effect only when x-oss-server-side-encryption is set to KMS. // metadata.setHeader("x-oss-server-side-encryption-key-id", "9468da86-3509-4f8d-a61e-6eab1eac****"); put.setMetadata(metadata); try { PutObjectResult putResult = oss.putObject(put); Log.d("PutObject", "UploadSuccess"); Log.d("ETag", putResult.getETag()); Log.d("RequestId", putResult.getRequestId()); } catch (ClientException e) { // Handle client-side exceptions, such as network errors. e.printStackTrace(); } catch (ServiceException e) { // Handle server-side exceptions. Log.e("RequestId", e.getRequestId()); Log.e("ErrorCode", e.getErrorCode()); Log.e("HostId", e.getHostId()); Log.e("RawMessage", e.getRawMessage()); }iOS
OSSPutObjectRequest * put = [OSSPutObjectRequest new]; // Specify the name of the bucket. Example: examplebucket. put.bucketName = @"examplebucket"; // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. put.objectKey = @"exampledir/exampleobject.txt"; put.uploadingFileURL = [NSURL fileURLWithPath:@"<filePath>"]; // put.uploadingData = <NSData *>; // Directly upload NSData. // (Optional) Configure an upload progress indicator. put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) { // Specify the number of bytes that are being uploaded, the number of bytes that are uploaded, and the total number of bytes that you want to upload. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend); }; // Configure optional fields. // put.contentType = @"application/octet-stream"; // Specify Content-MD5. // put.contentMd5 = @"eB5eJF1ptWaXm4bijSPyxw=="; // Specify the method that is used to encode the object. // put.contentEncoding = @"identity"; // Specify the method that is used to display the object content. // put.contentDisposition = @"attachment"; // Configure object metadata or HTTP headers. // NSMutableDictionary *meta = [NSMutableDictionary dictionary]; // Specify the object metadata. // [meta setObject:@"value" forKey:@"x-oss-meta-name1"]; // Set the access control list (ACL) of the object to private. // [meta setObject:@"private" forKey:@"x-oss-object-acl"]; // Set the storage class of the object to Standard. // [meta setObject:@"Standard" forKey:@"x-oss-storage-class"]; // Specify that this upload overwrites an existing object that has the same name. // [meta setObject:@"true" forKey:@"x-oss-forbid-overwrite"]; // Specify one or more tags for the object. // [meta setObject:@"a:1" forKey:@"x-oss-tagging"]; // Specify the server-side encryption algorithm that is used to encrypt the destination object when Object Storage Service (OSS) creates the object. // [meta setObject:@"AES256" forKey:@"x-oss-server-side-encryption"]; // Specify the customer master key (CMK) that is managed by Key Management Service (KMS). This parameter takes effect only if you set x-oss-server-side-encryption to KMS. // [meta setObject:@"9468da86-3509-4f8d-a61e-6eab1eac****" forKey:@"x-oss-server-side-encryption-key-id"]; // put.objectMeta = meta; OSSTask * putTask = [client putObject:put]; [putTask continueWithBlock:^id(OSSTask *task) { if (!task.error) { NSLog(@"upload object success!"); } else { NSLog(@"upload object failed, error: %@" , task.error); } return nil; }]; // waitUntilFinished blocks execution of the current thread but does not block the task progress. // [putTask waitUntilFinished]; // [put cancel];C++
#include <alibabacloud/oss/OssClient.h> #include <fstream> using namespace AlibabaCloud::OSS; int main(void) { /* Initialize information about the account that is used to access OSS. */ /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */ std::string Endpoint = "yourEndpoint"; /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */ std::string Region = "yourRegion"; /* Specify the name of the bucket. Example: examplebucket. */ std::string BucketName = "examplebucket"; /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */ std::string ObjectName = "exampledir/exampleobject.txt"; /* Initialize resources such as network resources. */ InitializeSdk(); ClientConfiguration conf; conf.signatureVersion = SignatureVersionType::V4; /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */ auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>(); OssClient client(Endpoint, credentialsProvider, conf); client.SetRegion(Region); /* Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. In this example, localpath indicates the local path in which the examplefile.txt file is stored. */ std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("D:\\localpath\\examplefile.txt", std::ios::in | std::ios::binary); PutObjectRequest request(BucketName, ObjectName, content); /* (Optional) Set the ACL to private and the storage class to Standard for the object. */ //request.MetaData().addHeader("x-oss-object-acl", "private"); //request.MetaData().addHeader("x-oss-storage-class", "Standard"); auto outcome = client.PutObject(request); if (!outcome.isSuccess()) { /* Handle exceptions. */ std::cout << "PutObject fail" << ",code:" << outcome.error().Code() << ",message:" << outcome.error().Message() << ",requestId:" << outcome.error().RequestId() << std::endl; return -1; } /* Release resources such as network resources. */ ShutdownSdk(); return 0; }C
#include "oss_api.h" #include "aos_http_io.h" /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */ const char *endpoint = "yourEndpoint"; /* Specify the name of the bucket. Example: examplebucket. */ const char *bucket_name = "examplebucket"; /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */ const char *object_name = "exampledir/exampleobject.txt"; const char *object_content = "More than just cloud."; /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */ const char *region = "yourRegion"; void init_options(oss_request_options_t *options) { options->config = oss_config_create(options->pool); /* Use a char* string to initialize data of the aos_string_t type. */ aos_str_set(&options->config->endpoint, endpoint); /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */ aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID")); aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET")); // Specify two additional parameters. aos_str_set(&options->config->region, region); options->config->signature_version = 4; /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */ options->config->is_cname = 0; /* Configure network parameters, such as the timeout period. */ options->ctl = aos_http_controller_create(options->pool, 0); } int main(int argc, char *argv[]) { /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */ if (aos_http_io_initialize(NULL, 0) != AOSE_OK) { exit(1); } /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */ aos_pool_t *pool; /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */ aos_pool_create(&pool, NULL); /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */ oss_request_options_t *oss_client_options; /* Allocate the memory resources in the memory pool to the options. */ oss_client_options = oss_request_options_create(pool); /* Initialize oss_client_options. */ init_options(oss_client_options); /* Initialize the parameters. */ aos_string_t bucket; aos_string_t object; aos_list_t buffer; aos_buf_t *content = NULL; aos_table_t *headers = NULL; aos_table_t *resp_headers = NULL; aos_status_t *resp_status = NULL; aos_str_set(&bucket, bucket_name); aos_str_set(&object, object_name); aos_list_init(&buffer); content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content)); aos_list_add_tail(&content->node, &buffer); /* Upload the object. */ resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, &buffer, headers, &resp_headers); /* Check whether the object is uploaded. */ if (aos_status_is_ok(resp_status)) { printf("put object from buffer succeeded\n"); } else { printf("put object from buffer failed\n"); } /* Release the memory pool. This operation releases the memory resources allocated for the request. */ aos_pool_destroy(pool); /* Release the allocated global resources. */ aos_http_io_deinitialize(); return 0; }Ruby
require 'aliyun/oss' client = Aliyun::OSS::Client.new( # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. endpoint: 'https://oss-cn-hangzhou.aliyuncs.com', # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. access_key_id: ENV['OSS_ACCESS_KEY_ID'], access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'] ) # Specify the name of the bucket. Example: examplebucket. bucket = client.get_bucket('examplebucket') # Upload the object. bucket.put_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')Upload a string
You can upload the content of a string from memory to OSS as a file.
Java
Before you begin, ensure that you have configured access credentials and installed the OSS SDK for Java V1.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.*; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build() try { // Specify the string that you want to upload. String content = "Hello OSS, hello world"; // Create a PutObjectRequest object. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes())); // The following sample code provides an example on how to specify the storage class and access control list (ACL) of an object when you upload the object: // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // Upload the string. PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } Python
Before you begin, ensure that you have configured credentials and installed the OSS SDK for Python.
import argparse import alibabacloud_oss_v2 as oss # Create a command line 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 directlyGo
Before you begin, ensure that you have configured credentials and installed the OSS SDK for Go.
package main import ( "context" "flag" "log" "strings" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Specify the global variables. var ( region string // The region in which the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // Specify the init function used to initialize command line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command line parameters. flag.Parse() // Check whether the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check whether the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check whether the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Specify the string that you want to upload. body := strings.NewReader("hi oss") // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSSClient instance. client := oss.NewClient(cfg) // Create a request to upload the local file. request := &oss.PutObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. Body: body, // The string that you want to upload. } // Execute the request to upload the local file. result, err := client.PutObject(context.TODO(), request) if err != nil { log.Fatalf("failed to put object %v", err) } // Display the result of the object upload operation. log.Printf("put object result:%#v\n", result) } PHP
<?php // Introduce autoload files to load dependent libraries. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Specify descriptions for command line parameters. $optsdesc = [ "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object. ]; // Convert the parameter descriptions to a long options list required by getopt. $longopts = \array_map(function ($key) { return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required. }, array_keys($optsdesc)); // Parse the command line parameters. $options = getopt("", $longopts); // Check whether the required parameters are configured. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain the help information about the parameters. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // If the required parameters are not configured, exit the program. } } // Obtain values from the parsed parameters. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. $key = $options["key"]; // The name of the object. // Obtain access credentials from environment variables. // Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configurations of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided. } // Create an OSSClient instance. $client = new Oss\Client($cfg); // Specify the content that you want to upload. $data = 'Hello OSS'; // Create a PutObjectRequest object to upload the local file. $request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key); $request-> body=Oss\Utils::streamFor($data); // Specify that the HTTP request body is a binary stream. // Execute the simple upload request. $result = $client->putObject($request); // Display the result of the simple upload request. printf( 'status code: %s' . PHP_EOL . // The HTTP status code. 'request id: %s' . PHP_EOL . // The request ID. 'etag: %s' . PHP_EOL, // The ETag of the object. $result->statusCode, $result->requestId, $result->etag ); Node.js
const OSS = require('ali-oss'); const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: 'yourregion', // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, authorizationV4: true, // Specify the name of your bucket. bucket: 'yourbucketname', }); async function putBuffer () { try { const result = await client.put('object-name', new Buffer.from('hello world')); console.log(result); } catch (e) { console.log(e); } } putBuffer();.NET
using System.Text; using Aliyun.OSS; using Aliyun.OSS.Common; // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. var endpoint = "yourEndpoint"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the name of the bucket. Example: examplebucket. var bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. var objectName = "exampledir/exampleobject.txt"; // Specify the string that you want to upload. var objectContent = "More than just cloud."; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters based on your requirements. var conf = new ClientConfiguration(); // Use the signature algorithm V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { byte[] binaryData = Encoding.ASCII.GetBytes(objectContent); MemoryStream requestContent = new MemoryStream(binaryData); // Upload the object. client.PutObject(bucketName, objectName, requestContent); Console.WriteLine("Put object succeeded"); } catch (Exception ex) { Console.WriteLine("Put object failed, {0}", ex.Message); }Upload a byte array
You can upload the content of a byte array in memory as a file. This method is suitable for scenarios where you need to flexibly process binary data before you upload it.
Python
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Python.
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 directlyGo
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Go.
package main import ( "bytes" "context" "flag" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Specify the global variables. var ( region string // The region in which the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // Specify the init function used to initialize command line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command line parameters. flag.Parse() // Check whether the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check whether the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check whether the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Specify the byte array that you want to upload. body := bytes.NewReader([]byte("yourObjectValueByteArray")) // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSSClient instance. client := oss.NewClient(cfg) // Create a request to upload the local file. request := &oss.PutObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. Body: body, // The string that you want to upload. } // Execute the request to upload the local file. result, err := client.PutObject(context.TODO(), request) if err != nil { log.Fatalf("failed to put object %v", err) } // Display the result of the object upload operation. log.Printf("put object result:%#v\n", result) } Android
byte[] uploadData = new byte[100 * 1024]; new Random().nextBytes(uploadData); // Construct an upload request. // Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. // Do not include the bucket name in the full path of the object. PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", uploadData); try { PutObjectResult putResult = oss.putObject(put); Log.d("PutObject", "UploadSuccess"); Log.d("ETag", putResult.getETag()); Log.d("RequestId", putResult.getRequestId()); } catch (ClientException e) { // Handle client-side exceptions, such as network errors. e.printStackTrace(); } catch (ServiceException e) { // Handle server-side exceptions. Log.e("RequestId", e.getRequestId()); Log.e("ErrorCode", e.getErrorCode()); Log.e("HostId", e.getHostId()); Log.e("RawMessage", e.getRawMessage()); }Upload a file stream
You can read data from a local or in-memory source and upload it as a file stream.
Java
Before you begin, make sure that you have configured access credentials and installed the OSS SDK for Java V1.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.FileInputStream; import java.io.InputStream; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. // If you do not specify the path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. String filePath= "D:\\localpath\\examplefile.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { InputStream inputStream = new FileInputStream(filePath); // Create a PutObjectRequest object. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // Create a PutObject request. PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } Node.js
const OSS = require('ali-oss'); const fs = require('fs'); const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: 'yourRegion', // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, authorizationV4: true, // Specify the name of the bucket. Example: examplebucket. bucket: 'examplebucket', }); async function putStream () { try { // Use chunked encoding. When you call putStream, OSS SDK initiates an HTTP PUT request for chunked encoding. // Specify the full path of the local file. Data stream is read from the local file. // If the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. let stream = fs.createReadStream('D:\\localpath\\examplefile.txt'); // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. let result = await client.putStream('exampledir/exampleobject.txt', stream); // Do not use chunked encoding. If contentLength is specified in options, chunked encoding is not used. // let stream = fs.createReadStream('D:\\localpath\\examplefile.txt'); // let size = fs.statSync('D:\\localpath\\examplefile.txt').size; // let result = await client.putStream( // You can set stream to specify the types of Readable Stream, such as file stream and network stream. // 'exampledir/exampleobject.txt', stream, {contentLength: size}); console.log(result); } catch (e) { console.log(e) } } putStream(); Ruby
require 'aliyun/oss' client = Aliyun::OSS::Client.new( # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. endpoint: 'https://oss-cn-hangzhou.aliyuncs.com', # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. access_key_id: ENV['OSS_ACCESS_KEY_ID'], access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'] ) # Specify the name of the bucket. Example: examplebucket. bucket = client.get_bucket('examplebucket') # Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt. bucket.put_object('exampleobject.txt') do |stream| 100.times { |i| stream << i.to_s } endUpload a network stream
You can read a data stream directly from the network and upload it to OSS. This method is suitable for transferring streaming data that does not need to be saved locally.
Java
Before you begin, make sure that you have configured access credentials and installed the OSS SDK for Java V1.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.InputStream; import java.net.URL; public class Demo { public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the URL of the network stream. String url = "https://www.aliyun.com/"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { InputStream inputStream = new URL(url).openStream(); // Create a PutObjectRequest object. PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // Create a PutObject request. PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } } Python
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Python.
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 directlyGo
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Go.
package main import ( "context" "flag" "io" "log" "net/http" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Specify the global variables. var ( region string // The region in which the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // Specify the init function used to initialize command line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command line parameters. flag.Parse() // Check whether the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check whether the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check whether the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSSClient instance. client := oss.NewClient(cfg) // Specify the network stream that you want to upload. resp, err := http.Get("https://www.aliyun.com/") if err != nil { log.Fatalf("Failed to fetch URL: %v", err) } defer resp.Body.Close() // Create a request to upload the local file. request := &oss.PutObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. Body: io.Reader(resp.Body), // The network stream that you want to upload. } // Execute the request to upload the local file. result, err := client.PutObject(context.TODO(), request) if err != nil { log.Fatalf("failed to put object %v", err) } // Display the result of the object upload operation. log.Printf("put object result:%#v\n", result) } Node.js
const OSS = require("ali-oss"); const fs = require("fs"); const urllib = require("urllib"); const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: 'yourRegion', // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, authorizationV4: true, // Specify the name of the bucket. Example: examplebucket. bucket: 'examplebucket', }); // Specify the network stream URL. const url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20220908/cbgh/IMG_example.jpg"; // Import the duplex stream. // You can set stream to specify the types of Readable Stream, such as file stream and network stream. const Duplex = require("stream").Duplex; // Instantiate the duplex stream. let stream = new Duplex(); urllib.request(url, (err, data, res) => { if (!err) { // Receive data from the duplex stream. stream.push(data); stream.push(null); client // Specify the full path of the object. Example: example.png. Do not include the bucket name in the full path. .putStream("example.png", stream) .then((r) => console.log(r)) .catch((e) => console.log(e)); } });PHP
<?php // Introduce autoload files to load dependent libraries. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Specify descriptions for command line parameters. $optsdesc = [ "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object. ]; // Convert the parameter descriptions to a long options list required by getopt. $longopts = \array_map(function ($key) { return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required. }, array_keys($optsdesc)); // Parse the command line parameters. $options = getopt("", $longopts); // Check whether the required parameters are configured. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain the help information about the parameters. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // If the required parameters are not configured, exit the program. } } // Obtain values from the parsed parameters. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. $key = $options["key"]; // The name of the object. // Obtain access credentials from environment variables. // Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configurations of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided. } // Create an OSSClient instance. $client = new Oss\Client($cfg); // Query the content of the network file. $url = 'https://www.aliyun.com/'; $response = file_get_contents($url); // Create a PutObjectRequest object to upload the local file. $request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key); $request->body = Oss\Utils::streamFor($response); // Specify that the HTTP request body is a binary stream. // Execute the simple upload request. $result = $client->putObject($request); // Display the result of the simple upload request. printf( 'status code: %s' . PHP_EOL . // The HTTP status code. 'request id: %s' . PHP_EOL . // The request ID. 'etag: %s' . PHP_EOL, // The ETag of the object. $result->statusCode, $result->requestId, $result->etag ); Show a progress bar
You can display the upload progress in real time.
Java
Before you begin, make sure that you have configured access credentials and installed the OSS SDK for Java V1.
For more information, see Upload progress bar for Java.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.event.ProgressEvent; import com.aliyun.oss.event.ProgressEventType; import com.aliyun.oss.event.ProgressListener; import com.aliyun.oss.model.PutObjectRequest; import java.io.File; // Use the ProgressListener method to use the progress bar. public class PutObjectProgressListenerDemo implements ProgressListener { private long bytesWritten = 0; private long totalBytes = -1; private boolean succeed = false; public static void main(String[] args) throws Exception { // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir\exampleobject.txt. String objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. String pathName = "D:\\localpath\\examplefile.txt"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Specify the parameters of the progress bar when you upload the object. In this example, PutObjectProgressListenerDemo specifies the name of the class that you want to call. Replace it with an actual class name. ossClient.putObject(new PutObjectRequest(bucketName,objectName, new File(pathName)). <PutObjectRequest>withProgressListener(new PutObjectProgressListenerDemo())); // Specify the parameters of the progress bar when you download the object. In this example, GetObjectProgressListenerDemo specifies the name of the class that you want to call. Replace it with an actual class name. // ossClient.getObject(new GetObjectRequest(bucketName,objectName). // <GetObjectRequest>withProgressListener(new GetObjectProgressListenerDemo())); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } public boolean isSucceed() { return succeed; } // Rewrite the callback method to use the progress bar. The following sample code provides an example: @Override public void progressChanged(ProgressEvent progressEvent) { long bytes = progressEvent.getBytes(); ProgressEventType eventType = progressEvent.getEventType(); switch (eventType) { case TRANSFER_STARTED_EVENT: System.out.println("Start to upload......"); break; case REQUEST_CONTENT_LENGTH_EVENT: this.totalBytes = bytes; System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS"); break; case REQUEST_BYTE_TRANSFER_EVENT: this.bytesWritten += bytes; if (this.totalBytes != -1) { int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes); System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")"); } else { System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)"); } break; case TRANSFER_COMPLETED_EVENT: this.succeed = true; System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total"); break; case TRANSFER_FAILED_EVENT: System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred"); break; default: break; } } }Go
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Go.
package main import ( "context" "flag" "fmt" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Specify the global variables. var ( region string // The region in which the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // Specify the init function used to initialize command line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command line parameters. flag.Parse() // Check whether the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check whether the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check whether the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSSClient instance. client := oss.NewClient(cfg) // Specify the path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt. localFile := "/Users/localpath/exampleobject.txt" // Create a request to upload the local file. putRequest := &oss.PutObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. ProgressFn: func(increment, transferred, total int64) { fmt.Printf("increment:%v, transferred:%v, total:%v\n", increment, transferred, total) }, // Specify a progress callback function that is used to query the upload progress. } // Execute the request to upload the local file. result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile) if err != nil { log.Fatalf("failed to put object from file %v", err) } // Display the result of the object upload operation. log.Printf("put object from file result:%#v\n", result) } PHP
<?php // Introduce autoload files to load dependent libraries. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Specify descriptions for command line parameters. $optsdesc = [ "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object. ]; // Convert the parameter descriptions to a long options list required by getopt. // Add a colon (:) to the end of each parameter to indicate that a value is required. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Parse the command line parameters. $options = getopt("", $longopts); // Check whether the required parameters are configured. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain the help information about the parameters. echo "Error: the following arguments are required: --$key, $help"; exit(1); // If the required parameters are not configured, exit the program. } } // Obtain values from the parsed parameters. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. $key = $options["key"]; // The name of the object. // Obtain access credentials from the EnvironmentVariableCredentialsProvider variables. // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are correctly configured. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load the default configurations of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. // If the endpoint parameter is provided, specify a custom domain name. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); } // Create an OSSClient instance. $client = new Oss\Client($cfg); // Specify the data content that you want to upload. $data = 'Hello OSS'; // Create a PutObjectRequest request and specify the bucket name and object name in the request. $request = new Oss\Models\PutObjectRequest($bucket, $key); // Convert the data content to a stream object. $request->body = Oss\Utils::streamFor($data); // Specify the upload progress callback function. $request->progressFn = function (int $increment, int $transferred, int $total) { echo sprint("Uploaded:%d" . PHP_EOL, $transferred); // The number of uploaded bytes. echo sprint("This upload:%d" . PHP_EOL, $increment); // The number of uploaded incremental bytes. echo sprint("Total data:%d" . PHP_EOL, $total); // The size of the total object. echo '-------------------------------------------'. PHP_EOL; // The dotted line delimiter. }; // Use the putObject method to upload the local file. $result = $client->putObject($request); // Display the result of the simple upload request. printf( 'status code: %s' . PHP_EOL, $result->statusCode . // The returned HTTP status code. 'request id: %s' . PHP_EOL, $result->requestId . // The request ID. 'etag: %s' . PHP_EOL, $result->etag // The ETag of the object. ); .NET
using System; using System.IO; using System.Text; using Aliyun.OSS; using Aliyun.OSS.Common; namespace PutObjectProgress { class Program { static void Main(string[] args) { Program.PutObjectProgress(); Console.ReadKey(); } public static void PutObjectProgress() { // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. var endpoint = "yourEndpoint"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the name of the bucket. var bucketName = "yourBucketName"; // Specify the full path of the object. Do not include the bucket name in the full path. var objectName = "yourObjectName"; // Specify the full path of the local file to upload. In this example, the path is set to D:\\localpath\\examplefile.txt. The local named examplefile.txt is stored in the D:\\localpath directory. var localFilename = "yourLocalFilename"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters based on your requirements. var conf = new ClientConfiguration(); // Use the signature algorithm V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); // Upload the object with the specified progress bar displayed. try { using (var fs = File.Open(localFilename, FileMode.Open)) { var putObjectRequest = new PutObjectRequest(bucketName, objectName, fs); putObjectRequest.StreamTransferProgress += streamProgressCallback; client.PutObject(putObjectRequest); } Console.WriteLine("Put object:{0} succeeded", objectName); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } // Obtain the progress of the upload task. private static void streamProgressCallback(object sender, StreamTransferProgressArgs args) { System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ", args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes); } } }Android
// Construct an upload request. // Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /storage/emulated/0/oss/examplefile.txt. // Do not include the bucket name in the full path of the object. PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt"); // Configure the progress callback function to display the progress bar. put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() { @Override public void onProgress(PutObjectRequest request, long currentSize, long totalSize) { // currentSize specifies the size of the uploaded part of the object. Unit: bytes. // totalSize specifies the total size of the object that you want to upload. Unit: bytes. Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize); } }); // Aasynchronously upload the local file. OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() { @Override public void onSuccess(PutObjectRequest request, PutObjectResult result) { Log.d("PutObject", "UploadSuccess"); Log.d("ETag", result.getETag()); Log.d("RequestId", result.getRequestId()); } @Override public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) { // Handle request exceptions. if (clientExcepion != null) { // Handle client exceptions, such as network exceptions. clientExcepion.printStackTrace(); } if (serviceException != null) { // Handle service exceptions. Log.e("ErrorCode", serviceException.getErrorCode()); Log.e("RequestId", serviceException.getRequestId()); Log.e("HostId", serviceException.getHostId()); Log.e("RawMessage", serviceException.getRawMessage()); } } }); // task.cancel(); // You can cancel the download task. // task.waitUntilFinished(); // Wait until the task is complete.C++
#include <alibabacloud/oss/OssClient.h> #include <fstream> using namespace AlibabaCloud::OSS; void ProgressCallback(size_t increment, int64_t transfered, int64_t total, void* userData) { // increment specifies the size of the data that is uploaded by the callback function. // transferred specifies the size of the uploaded data. // total specifies the total size of the object that you want to upload. std::cout << "ProgressCallback[" << userData << "] => " << increment <<" ," << transfered << "," << total << std::endl; } int main(void) { /* Initialize information about the account that is used to access OSS. */ /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */ std::string Endpoint = "yourEndpoint"; /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */ std::string Region = "yourRegion"; /* Specify the name of the bucket. Example: examplebucket. */ std::string BucketName = "examplebucket"; /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */ std::string ObjectName = "exampledir/exampleobject.txt"; /* Initialize resources such as network resources. */ InitializeSdk(); ClientConfiguration conf; conf.signatureVersion = SignatureVersionType::V4; /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */ auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>(); OssClient client(Endpoint, credentialsProvider, conf); client.SetRegion(Region); /* Set yourLocalFilename to the full path of the local file. */ std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("yourLocalFilename", std::ios::in|std::ios::binary); PutObjectRequest request(BucketName, ObjectName, content); TransferProgress progressCallback = { ProgressCallback , nullptr }; request.setTransferProgress(progressCallback); /* Upload the object. */ auto outcome = client.PutObject(request); if (!outcome.isSuccess()) { /* Handle exceptions. */ std::cout << "PutObject fail" << ",code:" << outcome.error().Code() << ",message:" << outcome.error().Message() << ",requestId:" << outcome.error().RequestId() << std::endl; return -1; } /* Release resources such as network resources. */ ShutdownSdk(); return 0; }iOS
OSSPutObjectRequest * put = [OSSPutObjectRequest new]; // Specify the name of the bucket. Example: examplebucket. put.bucketName = @"examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. put.objectKey = @"exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. // By default, if you do not specify the full path of the local file, the local file is uploaded from the path of the project to which the sample program belongs. put.uploadingFileURL = [NSURL fileURLWithPath:@"filePath"]; // Configure the progress callback function to display the progress bar. put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) { // Specify the number of bytes that are being uploaded, the total number of bytes that are uploaded, and the total number of bytes that you want to upload. NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend); }; OSSTask * putTask = [client putObject:put]; [putTask continueWithBlock:^id(OSSTask *task) { if (!task.error) { NSLog(@"upload object success!"); } else { NSLog(@"upload object failed, error: %@" , task.error); } return nil; }]; // Implement synchronous blocking to wait for the task to complete. // [putTask waitUntilFinished]; C
#include "oss_api.h" #include "aos_http_io.h" /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */ const char *endpoint = "yourEndpoint"; /* Specify the name of the bucket. Example: examplebucket. */ const char *bucket_name = "examplebucket"; /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */ const char *object_name = "exampledir/exampleobject.txt"; /* Specify the full path of the local file. */ const char *local_filename = "yourLocalFilename"; /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */ const char *region = "yourRegion"; void init_options(oss_request_options_t *options) { options->config = oss_config_create(options->pool); /* Use a char* string to initialize data of the aos_string_t type. */ aos_str_set(&options->config->endpoint, endpoint); /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */ aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID")); aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET")); // Specify two additional parameters. aos_str_set(&options->config->region, region); options->config->signature_version = 4; /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */ options->config->is_cname = 0; /* Configure network parameters such as the timeout period. */ options->ctl = aos_http_controller_create(options->pool, 0); } void percentage(int64_t consumed_bytes, int64_t total_bytes) { assert(total_bytes >= consumed_bytes); printf("%%%" APR_INT64_T_FMT "\n", consumed_bytes * 100 / total_bytes); } int main(int argc, char *argv[]) { /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */ if (aos_http_io_initialize(NULL, 0) != AOSE_OK) { exit(1); } /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */ aos_pool_t *pool; /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */ aos_pool_create(&pool, NULL); /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */ oss_request_options_t *oss_client_options; /* Allocate the memory resources in the memory pool to the options. */ oss_client_options = oss_request_options_create(pool); /* Initialize oss_client_options. */ init_options(oss_client_options); /* Initialize the parameters. */ aos_string_t bucket; aos_string_t object; aos_string_t file; aos_list_t resp_body; aos_table_t *resp_headers = NULL; aos_status_t *resp_status = NULL; aos_str_set(&bucket, bucket_name); aos_str_set(&object, object_name); aos_str_set(&file, local_filename); /* Upload the object with the specified progress bar displayed. */ resp_status = oss_do_put_object_from_file(oss_client_options, &bucket, &object, &file, NULL, NULL, percentage, &resp_headers, &resp_body); if (aos_status_is_ok(resp_status)) { printf("put object from file succeeded\n"); } else { printf("put object from file failed\n"); } /* Release the memory pool. This operation releases the memory resources allocated for the request. */ aos_pool_destroy(pool); /* Release the allocated global resources. */ aos_http_io_deinitialize(); return 0; }Upload callback
After a file is uploaded, a callback notifies the application server to perform subsequent processing. For more information about how callbacks work, see Callback.
Java
Before you begin, make sure that you have configured access credentials and installed the OSS SDK for Java V1.
import com.aliyun.oss.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.Callback; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import java.io.ByteArrayInputStream; public class Demo { public static void main(String[] args) throws Exception{ // Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used. String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // Specify the name of the bucket. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. String objectName = "exampledir/exampleobject.txt"; // Specify the address of the server to which the callback request is sent. Example: https://example.com:23450. String callbackUrl = "yourCallbackServerUrl"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. String region = "cn-hangzhou"; // Create an OSSClient instance. // Call the shutdown method to release associated resources when the OSSClient is no longer in use. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { String content = "Hello OSS"; PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,new ByteArrayInputStream(content.getBytes())); // Configure upload callback parameters. Callback callback = new Callback(); callback.setCallbackUrl(callbackUrl); // (Optional) Specify the CallbackHost field in the callback request header. // callback.setCallbackHost("yourCallbackHost"); // Set the callback request body in JSON format and define placeholder variables within. callback.setCalbackBodyType(Callback.CalbackBodyType.JSON); callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object},\\\"mimeType\\\":${mimeType},\\\"size\\\":${size},\\\"my_var1\\\":${x:var1},\\\"my_var2\\\":${x:var2}}"); // Configure custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:. callback.addCallbackVar("x:var1", "value1"); callback.addCallbackVar("x:var2", "value2"); putObjectRequest.setCallback(callback); // Perform the upload operation. PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest); // Read the message content returned from the upload callback. byte[] buffer = new byte[1024]; putObjectResult.getResponse().getContent().read(buffer); // You must close the obtained stream after the data is read. Otherwise, connection leaks may occur. Consequently, no connections are available and an exception occurs. putObjectResult.getResponse().getContent().close(); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (Throwable ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }Python
Before you begin, make sure that you have configured credentials and installed the OSS SDK for Python.
import base64 import argparse import alibabacloud_oss_v2 as oss parser = argparse.ArgumentParser(description="put object sample") # Add required parameters parser.add_argument('--region', help='The region in which the bucket is located.', required=True) parser.add_argument('--bucket', help='The name of the bucket.', required=True) parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS') parser.add_argument('--key', help='The name of the object.', required=True) parser.add_argument('--call_back_url', help='Callback server address.', required=True) def main(): args = parser.parse_args() # 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 begin, make sure that you have configured credentials and installed the OSS SDK for Go.
package main import ( "context" "encoding/base64" "encoding/json" "flag" "log" "strings" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) // Specify the global variables. var ( region string // The region in which the bucket is located. bucketName string // The name of the bucket. objectName string // The name of the object. ) // Specify the init function used to initialize command line parameters. func init() { flag.StringVar(®ion, "region", "", "The region in which the bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.") flag.StringVar(&objectName, "object", "", "The name of the object.") } func main() { // Parse command line parameters. flag.Parse() // Check whether the bucket name is empty. if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } // Check whether the region is empty. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } // Check whether the object name is empty. if len(objectName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, object name required") } // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) // Create an OSSClient instance. client := oss.NewClient(cfg) // Specify the callback parameters. callbackMap := map[string]string{ "callbackUrl": "http://example.com:23450", // Specify the URL of the callback server. Example: https://example.com:23450. "callbackBody": "bucket=${bucket}&object=${object}&size=${size}&my_var_1=${x:my_var1}&my_var_2=${x:my_var2}", // Specify the callback request body. "callbackBodyType": "application/x-www-form-urlencoded", // Specify the type of the callback request body. } // Convert the configurations of the callback parameters to a JSON string and encode the string in Base64 to pass the callback configurations. callbackStr, err := json.Marshal(callbackMap) if err != nil { log.Fatalf("failed to marshal callback map: %v", err) } callbackBase64 := base64.StdEncoding.EncodeToString(callbackStr) callbackVarMap := map[string]string{} callbackVarMap["x:my_var1"] = "thi is var 1" callbackVarMap["x:my_var2"] = "thi is var 2" callbackVarStr, err := json.Marshal(callbackVarMap) if err != nil { log.Fatalf("failed to marshal callback var: %v", err) } callbackVarBase64 := base64.StdEncoding.EncodeToString(callbackVarStr) // Specify the string that you want to upload. body := strings.NewReader("Hello, OSS!") // The string that you want to upload. // Create a request to upload the local file. request := &oss.PutObjectRequest{ Bucket: oss.Ptr(bucketName), // The name of the bucket. Key: oss.Ptr(objectName), // The name of the object. Body: body, // The object content. Callback: oss.Ptr(callbackBase64), // The callback parameters. CallbackVar: oss.Ptr(callbackVarBase64), } // Execute the request to upload the local file. result, err := client.PutObject(context.TODO(), request) if err != nil { log.Fatalf("failed to put object %v", err) } // Display the result of the object upload operation. log.Printf("put object result:%#v\n", result) } PHP
<?php // Introduce autoload files to load dependent libraries. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Specify descriptions for command line parameters. $optsdesc = [ "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS. "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket. "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the object. ]; // Convert the parameter descriptions to a long options list required by getopt. // Add a colon (:) to the end of each parameter to indicate that a value is required. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Parse the command line parameters. $options = getopt("", $longopts); // Check whether the required parameters are configured. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain the help information about the parameters. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // If the required parameters are not configured, exit the program. } } // Obtain values from the parsed parameters. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. $key = $options["key"]; // The name of the object. // Obtain access credentials from environment variables. // Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configurations of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided. } // Create an OSSClient instance. $client = new Oss\Client($cfg); // Specify the information about the callback server. // Specify the callback URL, which is the address of the server that receives the callback request. // Specify the callback host, which is the hostname of the callback server. // Specify the callback body, which is the template that is used to specify the callback content. A dynamic placeholder is supported. // Specify the type of the callback body, which is the format of the callback content. $callback = base64_encode(json_encode(array( 'callbackUrl' => yourCallbackServerUrl, // Replace yourCallbackServerUrl with the actual callback server URL. 'callbackHost' => 'CallbackHost', // Replace CallbackHost with the actual callback server hostname. 'callbackBody' => 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}', 'callbackBodyType' => "application/x-www-form-urlencoded", // Specify the format of the callback content. ))); // Specify custom variables to pass additional information in the callback. $callbackVar = base64_encode(json_encode(array( 'x:var1' => "value1", // Specify the first custom variable. 'x:var2' => 'value2', // Specify the second custom variable. ))); // Create a PutObjectRequest object to upload the local file. $request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key); $request->callback = $callback; // Specify callback information. $request->callbackVar = $callbackVar; // Specify the custom variables. // Execute the simple upload request. $result = $client->putObject($request); // Display the result of the simple upload request. // Display the HTTP status code, the request ID, and the callback result to check whether the request is successful. printf( 'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful. 'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request. 'callback result:' . var_export($result->callbackResult, true) . PHP_EOL // The details of the callback result. ); .NET
using System; using System.IO; using System.Text; using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; namespace Callback { class Program { static void Main(string[] args) { Program.PutObjectCallback(); Console.ReadKey(); } public static void PutObjectCallback() { // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the name of the bucket. Example: examplebucket. var bucketName = "examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. var objectName = "exampledir/exampleobject.txt"; // Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt. By default, if you do not specify the path of the local file, the file is uploaded from the local path of the project to which the sample program belongs. var localFilename = "D:\\localpath\\examplefile.txt"; // Specify the URL of the callback server. Example: https://example.com:23450. const string callbackUrl = "yourCallbackServerUrl"; // Specify the callbackBody field included in the callback request. const string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&" + "my_var1=${x:var1}&my_var2=${x:var2}"; // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters based on your requirements. var conf = new ClientConfiguration(); // Use the signature algorithm V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OSSClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { string responseContent = ""; var metadata = BuildCallbackMetadata(callbackUrl, callbackBody); using (var fs = File.Open(localFilename, FileMode.Open)) { var putObjectRequest = new PutObjectRequest(bucketName, objectName, fs, metadata); var result = client.PutObject(putObjectRequest); responseContent = GetCallbackResponse(result); } Console.WriteLine("Put object:{0} succeeded, callback response content:{1}", objectName, responseContent); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } // Configure an upload callback. private static ObjectMetadata BuildCallbackMetadata(string callbackUrl, string callbackBody) { string callbackHeaderBuilder = new CallbackHeaderBuilder(callbackUrl, callbackBody).Build(); string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder(). AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build(); var metadata = new ObjectMetadata(); metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder); metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder); return metadata; } // Read the response to the upload callback request. private static string GetCallbackResponse(PutObjectResult putObjectResult) { string callbackResponse = null; using (var stream = putObjectResult.ResponseStream) { var buffer = new byte[4 * 1024]; var bytesRead = stream.Read(buffer, 0, buffer.Length); callbackResponse = Encoding.Default.GetString(buffer, 0, bytesRead); } return callbackResponse; } } }Node.js
const OSS = require("ali-oss"); varpath = require("path"); const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: "yourregion", // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, authorizationV4: true, // Specify the name of the bucket. bucket: "examplebucket", }); const options = { callback: { // Specify the address of the callback server that receives the callback request. Example: http://oss-demo.aliyuncs.com:23450. url: "http://oss-demo.aliyuncs.com:23450", // (Optional) Specify the Host field included in the callback request header. //host: 'yourCallbackHost', // Specify the body of the callback request. body: "bucket=${bucket}&object=${object}&var1=${x:var1}&var2=${x:var2}", // Specify Content-Type in the callback request. contentType: "application/x-www-form-urlencoded", // Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client. callbackSNI: true, // Configure custom parameters for the callback request. customValue: { var1: "value1", var2: "value2", }, }, }; async function put() { try { // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. // By default, if you do not specify the path of the local file, the file is uploaded from the local path of the project to which the sample program belongs. let result = await client.put( "exampleobject.txt", path.normalize("/localpath/examplefile.txt"), options ); console.log(result); } catch (e) { console.log(e); } } put(); Ruby
require 'aliyun/oss' client = Aliyun::OSS::Client.new( # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. endpoint: 'https://oss-cn-hangzhou.aliyuncs.com', # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. access_key_id: ENV['OSS_ACCESS_KEY_ID'], access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'] ) # Specify the name of the bucket. Example: examplebucket. bucket = client.get_bucket('examplebucket') callback = Aliyun::OSS::Callback.new( url: 'http://oss-demo.aliyuncs.com:23450', query: {user: 'put_object'}, body: 'bucket=${bucket}&object=${object}' ) begin bucket.put_object('files/hello', file: '/tmp/x', callback: callback) rescue Aliyun::OSS::CallbackError => e puts "Callback failed: #{e.message}" endBrowser.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <button id="submit">Upload Callbacks</button> <!-- Import the SDK file --> <script type="text/javascript" src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.16.0.min.js" ></script> <script type="text/javascript"> const client = new OSS({ // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. region: "yourRegion", authorizationV4: true, // Specify the temporary AccessKey pair obtained from Security Token Service (STS). The AccessKey pair consists of an AccessKey ID and an AccessKey secret. accessKeyId: "yourAccessKeyId", accessKeySecret: "yourAccessKeySecret", // Specify the security token obtained from STS. stsToken: "yourSecurityToken", // Specify the name of the bucket. Example: examplebucket. bucket: "examplebucket", }); const options = { callback: { // Specify the public endpoint of the server that receives the callback request. url: "http://examplebucket.aliyuncs.com:23450", // Specify the Host field included in the callback request header. // host: 'yourHost', // Specify the body field included in the callback request. body: "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&var1=${x:var1}&var2=${x:var2}", // Specify the Content-Type field in the callback request. // contentType: 'application/x-www-form-urlencoded', // Specify whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client. callbackSNI: true, // Configure the custom parameters for the callback request. customValue: { var1: "value1", var2: "value2", }, }, }; // Query DOM. const submit = document.getElementById("submit"); // Implement the upload callback. submit.addEventListener("click", () => { client .put("example.txt", new Blob(["Hello World"]), options) .then((r) => console.log(r)); }); </script> </body> </html> Android
// Construct an upload request. // Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /storage/emulated/0/oss/examplefile.txt. // Do not include the bucket name in the full path of the object. PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt"); put.setCallbackParam(new HashMap<String, String>() { { put("callbackUrl", "http://oss-demo.aliyuncs.com:23450"); put("callbackHost", "yourCallbackHost"); put("callbackBodyType", "application/json"); put("callbackBody", "{\"mimeType\":${mimeType},\"size\":${size}}"); } }); OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() { @Override public void onSuccess(PutObjectRequest request, PutObjectResult result) { Log.d("PutObject", "UploadSuccess"); // Obtain the returned callback information. You can obtain the callback information only if you specify servercallback in the request. String serverCallbackReturnJson = result.getServerCallbackReturnBody(); Log.d("servercallback", serverCallbackReturnJson); } @Override public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) { // Handle exceptions. } }); C++
#include <alibabacloud/oss/OssClient.h> using namespace AlibabaCloud::OSS; int main(void) { /* Initialize information about the account that is used to access OSS. */ /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */ std::string Endpoint = "yourEndpoint"; /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */ std::string Region = "yourRegion"; /* Specify the name of the bucket. Example: examplebucket. */ std::string BucketName = "examplebucket"; /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */ std::string ObjectName = "exampledir/exampleobject.txt"; /* Specify the URL of the callback server. */ std::string ServerName = "https://example.aliyundoc.com:23450"; /* Initialize resources such as network resources. */ InitializeSdk(); ClientConfiguration conf; conf.signatureVersion = SignatureVersionType::V4; /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */ auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>(); OssClient client(Endpoint, credentialsProvider, conf); client.SetRegion(Region); std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>(); *content << "Thank you for using Aliyun Object Storage Service!"; /* Configure the upload callback parameters. */ std::string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var1=${x:var1}"; ObjectCallbackBuilder builder(ServerName, callbackBody, "", ObjectCallbackBuilder::Type::URL); std::string value = builder.build(); ObjectCallbackVariableBuilder varBuilder; varBuilder.addCallbackVariable("x:var1", "value1"); std::string varValue = varBuilder.build(); PutObjectRequest request(BucketName, ObjectName, content); request.MetaData().addHeader("x-oss-callback", value); request.MetaData().addHeader("x-oss-callback-var", varValue); auto outcome = client.PutObject(request); /* Release resources such as network resources. */ ShutdownSdk(); return 0; }iOS
OSSPutObjectRequest * request = [OSSPutObjectRequest new]; // Specify the name of the bucket. Example: examplebucket. request.bucketName = @"examplebucket"; // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. request.objectKey = @"exampledir/exampleobject.txt"; request.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"]; // Configure callback parameters. request.callbackParam = @{ @"callbackUrl": @"<your server callback address>", @"callbackBody": @"<your callback body>" }; // Specify custom variables. request.callbackVar = @{ @"<var1>": @"<value1>", @"<var2>": @"<value2>" }; request.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) { NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend); }; OSSTask * task = [client putObject:request]; [task continueWithBlock:^id(OSSTask *task) { if (task.error) { OSSLogError(@"%@", task.error); } else { OSSPutObjectResult * result = task.result; NSLog(@"Result - requestId: %@, headerFields: %@, servercallback: %@", result.requestId, result.httpResponseHeaderFields, result.serverReturnJsonString); } return nil; }]; // Implement synchronous blocking to wait for the task to complete. // [task waitUntilFinished]; C
#include "oss_api.h" #include "aos_http_io.h" /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */ const char *endpoint = "yourEndpoint"; /* Specify the name of the bucket. Example: examplebucket. */ const char *bucket_name = "examplebucket"; /* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */ const char *object_name = "exampledir/exampleobject.txt"; const char *object_content = "More than just cloud."; /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */ const char *region = "yourRegion"; void init_options(oss_request_options_t *options) { options->config = oss_config_create(options->pool); /* Use a char* string to initialize data of the aos_string_t type. */ aos_str_set(&options->config->endpoint, endpoint); /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */ aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID")); aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET")); // Specify two additional parameters. aos_str_set(&options->config->region, region); options->config->signature_version = 4; /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */ options->config->is_cname = 0; /* Configure network parameters, such as the timeout period. */ options->ctl = aos_http_controller_create(options->pool, 0); } int main(int argc, char *argv[]) { aos_pool_t *p = NULL; aos_status_t *s = NULL; aos_string_t bucket; aos_string_t object; aos_table_t *headers = NULL; oss_request_options_t *options = NULL; aos_table_t *resp_headers = NULL; aos_list_t resp_body; aos_list_t buffer; aos_buf_t *content; char *buf = NULL; int64_t len = 0; int64_t size = 0; int64_t pos = 0; char b64_buf[1024]; int b64_len; /* Specify the callback parameters in the JSON format. */ /* (Optional) Specify the Host field included in the callback request header. */ char *callback = "{" "\"callbackUrl\":\"http://oss-demo.aliyuncs.com:23450\"," "\"callbackHost\":\"yourCallbackHost\"," "\"callbackBody\":\"bucket=${bucket}&object=${object}&size=${size}&mimeType=${mimeType}\"," "\"callbackBodyType\":\"application/x-www-form-urlencoded\"" "}"; /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */ if (aos_http_io_initialize(NULL, 0) != AOSE_OK) { exit(1); } /* Initialize the parameters. */ aos_pool_create(&p, NULL); options = oss_request_options_create(p); init_options(options); aos_str_set(&bucket, bucket_name); aos_str_set(&object, object_name); aos_list_init(&resp_body); aos_list_init(&buffer); content = aos_buf_pack(options->pool, object_content, strlen(object_content)); aos_list_add_tail(&content->node, &buffer); /* Add the callback to the header. */ b64_len = aos_base64_encode((unsigned char*)callback, strlen(callback), b64_buf); b64_buf[b64_len] = '\0'; headers = aos_table_make(p, 1); apr_table_set(headers, OSS_CALLBACK, b64_buf); /* Configure the upload callback. */ s = oss_do_put_object_from_buffer(options, &bucket, &object, &buffer, headers, NULL, NULL, &resp_headers, &resp_body); if (aos_status_is_ok(s)) { printf("put object from buffer succeeded\n"); } else { printf("put object from buffer failed\n"); } /* Obtain the buffer length. */ len = aos_buf_list_len(&resp_body); buf = (char *)aos_pcalloc(p, (apr_size_t)(len + 1)); buf[len] = '\0'; /* Copy the content in the buffer to the memory. */ aos_list_for_each_entry(aos_buf_t, content, &resp_body, node) { size = aos_buf_size(content); memcpy(buf + pos, content->pos, (size_t)size); pos += size; } /* Release the memory pool. This operation releases the memory resources allocated for the request. */ aos_pool_destroy(p); /* Release the allocated global resources. */ aos_http_io_deinitialize(); return 0; }Use ossutil
Before you use the put-object command, make sure that you have installed ossutil.
Examples
Upload an object by uploading a string.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss"Upload an object by uploading a local file.
ossutil api put-object --bucket examplebucket --key exampleobject --body file://uploadFileUpload an object by uploading a string and specify the metadata of the object.
ossutil api put-object --bucket examplebucket --key exampleobject --metadata user=aliyun --metadata email=ali***@aliyuncs.com --body "hi oss"Upload an object by uploading a string and specify tags for the object.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --tagging "TagA=A&TagB=B"Upload an object by uploading a string and specify the ACL and storage class of the object.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --object-acl private --storage-class IAUpload an object by uploading a string and specify the method that is used to encrypt the object.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --server-side-encryption KMS --server-side-data-encryption SM4 --server-side-encryption-key-id 9468da86-3509-4f8d-a61e-6eab1eac****Upload an object by uploading a string and prevent the object that you want to upload from overwriting existing objects that have the same name.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --forbid-overwrite trueUpload an object by uploading a string and specify the caching behavior of the web page when the object is downloaded.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --cache-control no-cacheUpload an object by uploading a string and specify the name of the object when the object is downloaded.
ossutil api put-object --bucket examplebucket --key exampleobject --body "hi oss" --content-disposition "attachment;filename=oss_download.jpg"
Related API operations
The preceding methods are based on API operations. If your program has advanced custom requirements, you can make REST API requests directly. If you make REST API requests directly, you must manually write code to calculate signatures. 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
When you upload a file to OSS using simple upload, fees are incurred for the following billable items. For more information about the pricing of these billable items, see Pricing of OSS.
API | Billable item | Description |
PutObject | PUT requests | You are charged request fees based on the number of successful requests. |
Storage fees | You are charged storage fees based on the storage class, size, and storage duration of the object. |
FAQ
How do I upload a file that is larger than 5 GB?
Simple upload supports files up to 5 GB in size. To upload files larger than 5 GB, you can use multipart upload.
How do I upload multiple files at a time?
Use the OSS console (supports manual file selection)
Click the name of the destination bucket. Click Upload > Scan Folders. Select the folder, remove any unwanted files, and then click Upload.
Use ossbrowser (does not support file selection)
Click the name of the destination bucket. At the top of the page, click Upload and select Upload Folder from the drop-down list.
Use ossutil (supports filtering by filename)
You can use the cp command of ossutil with the -r (--recursive) option to upload multiple files to OSS at a time. You can also use the --include and --exclude options to filter files by name. For more information, see cp.
Upload files from the on-premises folder localfolder to the desfolder folder in the examplebucket bucket.
ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/Upload files that meet specific criteria.
Upload all files that have the TXT format.
ossutil cp -r D:/localpath/localfolder/ oss://examplebucket/desfolder/ --include "*.txt"
ZIP package decompression
You can use the ZIP package decompression feature for batch uploads. First, set the decompression rules. Then, package your files into a ZIP file and upload the file to OSS. This upload triggers Function Compute, which unzips the package and uploads the files to OSS. For more information, see ZIP package decompression.
How to share OSS resources with third parties for temporary access
OSS provides two methods to grant temporary access to third parties:
Presigned URLs
You can use a presigned URL to grant a third party temporary permission to upload or download a specific file. For more information, see Upload a file using a presigned URL and Download a file using a presigned URL.
STS temporary access credentials
To allow a third party to perform more OSS resource management operations in addition to uploading and downloading, such as listing or copying files, you can use Security Token Service (STS) temporary access credentials. For more information, see Use STS temporary access credentials to access OSS.
How to process uploaded files?
Image processing: To compress images, add custom styles, or retrieve image size information, see Image processing.
ApsaraVideo Media Processing: To recognize text, extract captions, transcode videos, or generate thumbnails for uploaded images and videos, see ApsaraVideo Media Processing.
How to perform a simple upload using a custom domain name
When you create an OssClient using an SDK, specify a custom domain name. For more information, see Access OSS using a custom domain name. In the configuration for each language, set the cname parameter to true.
How to prevent files from being accidentally overwritten?
By default, a simple upload overwrites an Object with the same name. To prevent accidental overwrites, you can use one of the following methods.
Enable versioning
After you enable versioning, overwritten objects are saved as previous versions. You can restore a previous version of an object at any time. For more information, see Introduction to versioning.
Include the x-oss-forbid-overwrite parameter in the upload request
In the header of the upload request, include the x-oss-forbid-overwrite parameter and set its value to true. If an object with the same name already exists in OSS, the upload fails and the
FileAlreadyExistserror is returned. If this parameter is not included or its value is false, the object with the same name is overwritten.
How to reduce PUT request fees
If you want to upload a large number of objects and set the storage classes of the objects to Deep Cold Archive, you are charged high PUT request fees. We recommend that you set the storage classes of the objects to Standard when you upload the objects, and configure lifecycle rules to convert the storage classes of the Standard objects to Deep Cold Archive. This reduces PUT request fees.
What happens when multiple users upload an object with the same name and path?
The result depends on whether versioning is enabled:
When versioning is disabled or paused: If multiple users upload an object with the same name, the object that finishes uploading last overwrites the previous one. Only the last uploaded object is retained. For example, if User A finishes uploading after User B, the object from User A is retained.
When versioning is enabled: Uploading an object with the same name creates a new version, which is identified by a version ID. OSS determines the latest version based on the upload start time. For example, if User B starts uploading after User A, the object uploaded by User B is marked as the latest version.
How to optimize upload performance
Uploading many objects that have sequential prefixes in their names, such as timestamps or alphabetical characters, can reduce the request rate. This is because the indexes for these objects are all stored in a single partition of the bucket. To improve performance, use random prefixes instead of sequential ones. For more information, see OSS performance best practices.