Object Storage Service (OSS) lets you use object tagging to classify objects in buckets. You can set lifecycle rules, access permissions, and other configurations for objects that have the same tags.
For more information about object tagging, see Object tagging.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.
In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.
To set object tags, you must have the
oss:PutObjectTaggingpermission. For more information, see Attach a custom policy to a RAM user.
Add object tags when you upload an object
The following examples show how to add tags to an object when you upload it using simple upload, multipart upload, append upload, and resumable upload.
Add object tags during a simple upload
The following code shows how to add tags during a simple upload.
using System.Text; using Aliyun.OSS; using System.Text; using Aliyun.OSS.Util; using Aliyun.OSS.Common; // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 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 set. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the bucket name. var bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. var objectName = "exampleobject.txt"; var objectContent = "More than just cloud."; String UrlEncodeKey(String key) { const string CharsetName = "utf-8"; const char separator = '/'; var segments = key.Split(separator); var encodedKey = new StringBuilder(); encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName)); for (var i = 1; i < segments.Length; i++) encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName)); if (key.EndsWith(separator.ToString())) { // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array, // so we have to append all the trailing slash to the uri. foreach (var ch in key) { if (ch == separator) encodedKey.Append(separator); else break; } } return encodedKey.ToString(); } // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters as needed. var conf = new ClientConfiguration(); // Use Signature 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); var meta = new ObjectMetadata(); // Set the tag information in the HTTP header. string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2"); meta.AddHeader("x-oss-tagging", str); var putRequest = new PutObjectRequest(bucketName, objectName, requestContent); putRequest.Metadata = meta; // Add tags to the file during the upload. client.PutObject(putRequest); Console.WriteLine("Put object succeeded"); } catch (Exception ex) { Console.WriteLine("Put object failed, {0}", ex.Message); }Add object tags during a multipart upload
The following code shows how to add tags during a multipart upload.
using Aliyun.OSS; using Aliyun.OSS.Util; using System.Text; using Aliyun.OSS.Common; // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 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 set. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the bucket name. var bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. var objectName = "exampleobject.txt"; // Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the sample program. var localFilename = "D:\\localpath\\examplefile.txt"; String UrlEncodeKey(String key) { const string CharsetName = "utf-8"; const char separator = '/'; var segments = key.Split(separator); var encodedKey = new StringBuilder(); encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName)); for (var i = 1; i < segments.Length; i++) encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName)); if (key.EndsWith(separator.ToString())) { // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array, // so we have to append all the trailing slash to the uri. foreach (var ch in key) { if (ch == separator) encodedKey.Append(separator); else break; } } return encodedKey.ToString(); } // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters as needed. var conf = new ClientConfiguration(); // Use Signature V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OssClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); // Initialize the multipart upload. var uploadId = ""; try { // Specify the name of the object to upload and the bucket to which it belongs. You can set ObjectMeta in InitiateMultipartUploadRequest, but you do not need to specify ContentLength. var request = new InitiateMultipartUploadRequest(bucketName, objectName); var meta = new ObjectMetadata(); // Set the tag information in the HTTP header. string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2"); meta.AddHeader("x-oss-tagging", str); request.ObjectMetadata = meta; var result = client.InitiateMultipartUpload(request); uploadId = result.UploadId; // Print the UploadId. Console.WriteLine("Init multi part upload succeeded"); Console.WriteLine("Upload Id:{0}", result.UploadId); } catch (Exception ex) { Console.WriteLine("Init multi part upload failed, {0}", ex.Message); } // Calculate the total number of parts. var partSize = 100 * 1024; var fi = new FileInfo(localFilename); var fileSize = fi.Length; var partCount = fileSize / partSize; if (fileSize % partSize != 0) { partCount++; } // Start the multipart upload. partETags is a list that stores partETags. After OSS receives the part list that you submit, it verifies the validity of each data part. After all data parts are verified, OSS combines these parts into a complete file. var partETags = new List<PartETag>(); try { using (var fs = File.Open(localFilename, FileMode.Open)) { for (var i = 0; i < partCount; i++) { var skipBytes = (long)partSize * i; // Go to the start position of the current upload. fs.Seek(skipBytes, 0); // Calculate the size of the part to upload. The last part is the remaining data. var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); var request = new UploadPartRequest(bucketName, objectName, uploadId) { InputStream = fs, PartSize = size, PartNumber = i + 1 }; // Call the UploadPart operation to upload the part. The return value contains the ETag of the part. var result = client.UploadPart(request); partETags.Add(result.PartETag); Console.WriteLine("finish {0}/{1}", partETags.Count, partCount); } Console.WriteLine("Put multi part upload succeeded"); } } catch (Exception ex) { Console.WriteLine("Put multi part upload failed, {0}", ex.Message); } // Complete the multipart upload. try { var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId); foreach (var partETag in partETags) { completeMultipartUploadRequest.PartETags.Add(partETag); } var result = client.CompleteMultipartUpload(completeMultipartUploadRequest); Console.WriteLine("complete multi part succeeded"); } catch (Exception ex) { Console.WriteLine("complete multi part failed, {0}", ex.Message); }Add object tags during an append upload
The following example shows how to add tags during an append upload.
using Aliyun.OSS; using Aliyun.OSS.Util; using System.Text; using Aliyun.OSS.Common; // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 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 set. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the bucket name. var bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. var objectName = "exampleobject.txt"; // Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the sample program. var localFilename = "D:\\localpath\\examplefile.txt"; String UrlEncodeKey(String key) { const string CharsetName = "utf-8"; const char separator = '/'; var segments = key.Split(separator); var encodedKey = new StringBuilder(); encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName)); for (var i = 1; i < segments.Length; i++) encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName)); if (key.EndsWith(separator.ToString())) { // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array, // so we have to append all the trailing slash to the uri. foreach (var ch in key) { if (ch == separator) encodedKey.Append(separator); else break; } } return encodedKey.ToString(); } // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters as needed. var conf = new ClientConfiguration(); // Use Signature V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OssClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); // The position of the first append is 0. The return value is the position for the next append. Subsequent appends start from the end of the file. long position = 0; try { var metadata = client.GetObjectMetadata(bucketName, objectName); position = metadata.ContentLength; } catch (Exception) { } try { using (var fs = File.Open(localFilename, FileMode.Open)) { var request = new AppendObjectRequest(bucketName, objectName) { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position }; var meta = new ObjectMetadata(); // Set the tag information in the HTTP header. string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2"); meta.AddHeader("x-oss-tagging", str); request.ObjectMetadata = meta; // First append. Only the tags set during the first append upload take effect. var result = client.AppendObject(request); // Set the append position for the file. position = result.NextAppendPosition; Console.WriteLine("Append object succeeded, next append position:{0}", position); } // Get the append position and append the file again. using (var fs = File.Open(localFilename, FileMode.Open)) { var request = new AppendObjectRequest(bucketName, objectName) { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position }; var result = client.AppendObject(request); position = result.NextAppendPosition; Console.WriteLine("Append object succeeded, next append position:{0}", position); } } catch (Exception ex) { Console.WriteLine("Append object failed, {0}", ex.Message); }Add object tags during a resumable upload
The following code shows how to add tags during a resumable upload.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; using System.Text; // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 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 set. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the bucket name. var bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. var objectName = "exampleobject.txt"; // Specify the full path of the local file, for example, D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the sample program. var localFilename = "D:\\localpath\\examplefile.txt"; // The file that records the multipart upload results. The upload progress is saved to this file. string checkpointDir = "yourCheckpointDir"; String UrlEncodeKey(String key) { const string CharsetName = "utf-8"; const char separator = '/'; var segments = key.Split(separator); var encodedKey = new StringBuilder(); encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName)); for (var i = 1; i < segments.Length; i++) encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName)); if (key.EndsWith(separator.ToString())) { // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array, // so we have to append all the trailing slash to the uri. foreach (var ch in key) { if (ch == separator) encodedKey.Append(separator); else break; } } return encodedKey.ToString(); } // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters as needed. var conf = new ClientConfiguration(); // Use Signature V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OssClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { // Set multiple parameters through UploadFileRequest. UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename) { // Specify the size of each part. PartSize = 8 * 1024 * 1024, // Specify the number of concurrent threads. ParallelThreadCount = 3, // checkpointDir specifies the file that records the results of the local multipart upload. The upload progress is saved to this file. If a part fails to be uploaded, the upload resumes from the recorded breakpoint. If checkpointDir is set to null, the resumable upload feature is disabled. If an upload fails, it restarts from the beginning. CheckpointDir = checkpointDir, }; var meta = new ObjectMetadata(); // Set the tag information in the HTTP header. string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2"); meta.AddHeader("x-oss-tagging", str); request.Metadata = meta; // Perform a resumable upload. client.ResumableUploadObject(request); Console.WriteLine("Resumable upload 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); }
Add or change object tags for an uploaded object
The following code shows how to add or change object tags for an existing object.
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
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 set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name.
var objectName = "exampleobject.txt";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Set the tag information.
var setRequest = new SetObjectTaggingRequest(bucketName, objectName);
var tag1 = new Tag
{
Key = "project",
Value = "projectone"
};
var tag2 = new Tag
{
Key = "user",
Value = "jsmith"
};
setRequest.AddTag(tag1);
setRequest.AddTag(tag2);
client.SetObjectTagging(setRequest);
Console.WriteLine("set object tagging succeeded");
}
catch (Exception ex)
{
Console.WriteLine("set object tagging failed. {0}", ex.Message);
}Set object tags when you copy an object
You can use the one of following methods to configure object tagging when you copy an object:
Copy: The tag of the source object is copied to the destination object.
Replace: The destination object has the tag specified in the request instead of the tag of the source object.
The following examples show how to set object tags when you copy an object that is smaller than 1 GB using simple copy and an object that is larger than 1 GB using multipart copy.
The following code shows how to set object tags when you copy an object smaller than 1 GB:
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; using System.Text; // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 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 set. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the name of the source bucket, for example, srcexamplebucket. var sourceBucket = "srcexamplebucket"; // Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt. var sourceObject = "srcdir/scrobject.txt"; // Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket. var targetBucket = "destbucket"; // Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt. var targetObject = "destdir/destobject.txt"; String UrlEncodeKey(String key) { const string CharsetName = "utf-8"; const char separator = '/'; var segments = key.Split(separator); var encodedKey = new StringBuilder(); encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName)); for (var i = 1; i < segments.Length; i++) encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName)); if (key.EndsWith(separator.ToString())) { // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array, // so we have to append all the trailing slash to the uri. foreach (var ch in key) { if (ch == separator) encodedKey.Append(separator); else break; } } return encodedKey.ToString(); } // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters as needed. var conf = new ClientConfiguration(); // Use Signature V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OssClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { var metadata = new ObjectMetadata(); metadata.AddHeader("mk1", "mv1"); metadata.AddHeader("mk2", "mv2"); // Set the tag information in the HTTP header. string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2"); metadata.AddHeader("x-oss-tagging", str); var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject) { // If NewObjectMetadata is null, the copy mode is used, which means the metadata of the source file is copied. If NewObjectMetadata is not null, the replace mode is used, which means the metadata of the source file is overwritten. NewObjectMetadata = metadata }; // Copy the file. client.CopyObject(req); Console.WriteLine("Copy object succeeded"); } 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); }The following code shows how to set object tags when you copy an object larger than 1 GB using a multipart copy:
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; using System.Text; // Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. 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 set. var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // Specify the name of the source bucket, for example, srcexamplebucket. var sourceBucket = "srcexamplebucket"; // Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt. var sourceObject = "srcdir/scrobject.txt"; // Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket. var targetBucket = "destbucket"; // Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt. var targetObject = "destdir/destobject.txt"; var uploadId = ""; var partSize = 50 * 1024 * 1024; String UrlEncodeKey(String key) { const string CharsetName = "utf-8"; const char separator = '/'; var segments = key.Split(separator); var encodedKey = new StringBuilder(); encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName)); for (var i = 1; i < segments.Length; i++) encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName)); if (key.EndsWith(separator.ToString())) { // String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array, // so we have to append all the trailing slash to the uri. foreach (var ch in key) { if (ch == separator) encodedKey.Append(separator); else break; } } return encodedKey.ToString(); } // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; // Create a ClientConfiguration instance and modify the default parameters as needed. var conf = new ClientConfiguration(); // Use Signature V4. conf.SignatureVersion = SignatureVersion.V4; // Create an OssClient instance. var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { // Initialize the copy task. You can use InitiateMultipartUploadRequest to specify the metadata of the destination object. var request = new InitiateMultipartUploadRequest(targetBucket, targetObject); var meta = new ObjectMetadata(); // Set the tag information in the HTTP header. string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2"); meta.AddHeader("x-oss-tagging", str); request.ObjectMetadata = meta; var result = client.InitiateMultipartUpload(request); // Print the uploadId. uploadId = result.UploadId; Console.WriteLine("Init multipart upload succeeded, Upload Id: {0}", result.UploadId); // Calculate the number of parts. var metadata = client.GetObjectMetadata(sourceBucket, sourceObject); var fileSize = metadata.ContentLength; var partCount = (int)fileSize / partSize; if (fileSize % partSize != 0) { partCount++; } // Start the multipart copy. var partETags = new List<PartETag>(); for (var i = 0; i < partCount; i++) { var skipBytes = (long)partSize * i; var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); // Create an UploadPartCopyRequest and specify the conditions in the request. var uploadPartCopyRequest = new UploadPartCopyRequest(targetBucket, targetObject, sourceBucket, sourceObject, uploadId) { PartSize = size, PartNumber = i + 1, // BeginIndex specifies the start position of the part to copy. BeginIndex = skipBytes }; // Call the uploadPartCopy method to copy each part. var uploadPartCopyResult = client.UploadPartCopy(uploadPartCopyRequest); Console.WriteLine("UploadPartCopy : {0}", i); partETags.Add(uploadPartCopyResult.PartETag); } // Complete the multipart copy. var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(targetBucket, targetObject, uploadId); // partETags is a list of partETags saved during the multipart upload. After OSS receives the list that you submit, it verifies the validity of each data part. After all parts are verified, OSS combines them into a complete file. foreach (var partETag in partETags) { completeMultipartUploadRequest.PartETags.Add(partETag); } var completeMultipartUploadResult = client.CompleteMultipartUpload(completeMultipartUploadRequest); Console.WriteLine("CompleteMultipartUpload succeeded"); } 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); }
Set tags for a symbolic link
The following code shows how to set object tags for a symbolic link.
using Aliyun.OSS;
using Aliyun.OSS.Util;
using System.Text;
using Aliyun.OSS.Common;
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
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 set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the bucket name.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name.
var targetObjectName = "exampleobject.txt";
// Specify the name of the symbolic link, for example, symlink.txt.
var symlinkObjectName = "symlink.txt";
var objectContent = "More than just cloud.";
String UrlEncodeKey(String key)
{
const string CharsetName = "utf-8";
const char separator = '/';
var segments = key.Split(separator);
var encodedKey = new StringBuilder();
encodedKey.Append(HttpUtils.EncodeUri(segments[0], CharsetName));
for (var i = 1; i < segments.Length; i++)
encodedKey.Append(separator).Append(HttpUtils.EncodeUri(segments[i], CharsetName));
if (key.EndsWith(separator.ToString()))
{
// String#split ignores trailing empty strings, e.g., "a/b/" will be split as a 2-entries array,
// so we have to append all the trailing slash to the uri.
foreach (var ch in key)
{
if (ch == separator)
encodedKey.Append(separator);
else
break;
}
}
return encodedKey.ToString();
}
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();
// Use Signature V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Upload the target object.
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
client.PutObject(bucketName, targetObjectName, requestContent);
var meta = new ObjectMetadata();
// Set the tag information in the HTTP header.
string str = UrlEncodeKey("key1") + "=" + UrlEncodeKey("value1") + "&" + UrlEncodeKey("key2") + "=" + UrlEncodeKey("value2");
meta.AddHeader("x-oss-tagging", str);
var request = new CreateSymlinkRequest(bucketName, symlinkObjectName, targetObjectName);
request.ObjectMetadata = meta;
// Create the symbolic link.
client.CreateSymlink(request);
// Get the name of the target object to which the symbolic link points.
var ossSymlink = client.GetSymlink(bucketName, symlinkObjectName);
Console.WriteLine("Target object is {0}", ossSymlink.Target);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}References
For information about the API operation that is used to set object tags, see PutObjectTagging.