Streaming download allows you to download an object as streams in increments. If you want to download a large object or if the download requires a long period of time to complete, you can perform streaming download to download the object in increments.
Usage notes
In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, 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 use streaming download, you must have the
oss:GetObject
permission. For more information, see Common examples of RAM policies.
Sample code
The following code provides an example on how to download an object to a stream:
using Aliyun.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.
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. Example: D:\\localpath\\examplefile.txt.
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// Download the object to a stream. OssObject includes object information such as the bucket where the object is stored, object name, object metadata, and an input stream.
var obj = client.GetObject(bucketName, objectName);
using (var requestStream = obj.Content)
{
byte[] buf = new byte[1024];
var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
var len = 0;
// The input stream can be used to read and download the object content to a local file or to the memory.
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
Console.WriteLine("Get object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Get object failed. {0}", ex.Message);
}