You can configure a progress bar to display the progress of an upload or download task. This topic describes how to configure a progress bar when you call the PutObject operation to upload an object.
Sample code
The following code provides an example on how to configure a progress bar to display the progress of an upload task:
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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket.
var bucketName = "yourBucketName";
// Specify the full path of the object. The full path cannot contain the bucket name.
var objectName = "yourObjectName";
// Specify the full path of the local file that you want 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";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
// Configure a progress bar while uploading the object.
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);
}
}
}
References
For the complete sample code of progress bars used for object upload, visit GitHub.