Simple download allows you to call the GetObject operation to download an object from an Object Storage Service (OSS) bucket by making an HTTP request.
Prerequisites
An object is uploaded to a bucket. For more information, see Upload objects.
An Archive object is restored or real-time access of Archive objects is enabled for the bucket that stores the Archive object if you want to download the Archive object. For more information, see Restore objects and Real-time access of Archive objects.
A Cold Archive or Deep Cold Archive object is restored if you want to download the object. For more information, see Restore objects.
Methods
Use the OSS console
You cannot download a directory or its subdirectories by using the OSS console. If you want to download a directory or its subdirectories, you can use ossbrowser, ossutil, OSS SDKs, API operations, or other supported methods.
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
Download objects.
Download a single object
Method 1: Choose
> Download in the Actions column of the object that you want to download.
NoteIf you have moved the download option from the default Added to More section to the Common object operations section, you can view the download option without the need to expand the
icon.
Method 2: Click the name of the object that you want to download, or click View Details in the Actions column. In the View Details panel, click Download.
Download multiple objects at a time
Select the objects that you want to download and click Download below the object list. You can download up to 100 objects at a time in the OSS console.
Use ossbrowser
You can use ossbrowser to perform the same object-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to download objects. For more information, see Use ossbrowser.
Use OSS SDKs
The following sample code provides examples on how to perform simple download by using OSS SDKs for common programming languages. For more information about how to perform simple download by using OSS SDKs for other programming languages, see Overview.
package com.aliyun.oss.demo;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
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: testfolder/exampleobject.txt.
String objectName = "testfolder/exampleobject.txt";
// Specify the full path of the local file to which you want to download the object.
String pathName = "D:\\localpath\\examplefile.txt";
// Specify the region in which the bucket is located. For example, if your bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Download the object to the specified path. If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path.
// If you do not specify the local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
} 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();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// 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.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt.
$object = "testfolder/exampleobject.txt";
// Download the object to D:\\localpath as a local file named examplefile.txt. If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path.
// If you do not specify the local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
$localfile = "D:\\localpath\\examplefile.txt";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $localfile
);
// Use try-catch to catch exceptions. If an exception is caught, the object fails to be downloaded. If no exceptions are caught, the object is downloaded.
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->getObject($bucket, $object, $options);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK, please check localfile: 'examplefile.txt'" . "\n");
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,
// Specify the name of the bucket.
bucket: 'examplebucket'
});
async function get () {
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 a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved as a local file.
// If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
const result = await client.get('exampleobject.txt', 'D:\\localpath\\examplefile.txt');
console.log(result);
} catch (e) {
console.log(e);
}
}
get();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Create a server object.
# 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.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint for 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.
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt.
# Download the object to your local computer and save the object to the D:\\localpath\\examplefile.txt path. If a file that has the same name already exists, the downloaded object overwrites the file. If no file that has the same name exists, the downloaded object is saved in the path.
bucket.get_object_to_file('testfolder/exampleobject.txt', 'D:\\localpath\\examplefile.txt')
print("Download complete.")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<!-- Import the SDK file -->
<script
type="text/javascript"
src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.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 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.
bucket: "examplebucket",
});
// Set the response header to automatically download an object by using the URL, and set the name of the local file after the object is downloaded.
const filename = "examplefile.txt";
const response = {
"content-disposition": `attachment; filename=${encodeURIComponent(
filename
)}`,
};
// Specify the full path of the object. Do not include the bucket name in the full path.
const url = client.signatureUrl("exampleobject.txt", { response });
console.log(url);
</script>
</body>
</html>
// Construct an object download 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.
GetObjectRequest get = new GetObjectRequest("examplebucket", "exampledir/exampleobject.txt");
oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
@Override
public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// Start reading data.
long length = result.getContentLength();
if (length > 0) {
byte[] buffer = new byte[(int) length];
int readCount = 0;
while (readCount < length) {
try{
readCount += result.getObjectContent().read(buffer, readCount, (int) length - readCount);
}catch (Exception e){
OSSLog.logInfo(e.toString());
}
}
// Specify the full path of the downloaded object. Example: D:\\localpath\\exampleobject.jpg.
try {
FileOutputStream fout = new FileOutputStream("download_filePath");
fout.write(buffer);
fout.close();
} catch (Exception e) {
OSSLog.logInfo(e.toString());
}
}
}
@Override
public void onFailure(GetObjectRequest request, ClientException clientException,
ServiceException serviceException) {
}
});
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
// 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. Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the name of the bucket. Example: examplebucket.
bucketName := "examplebucket" // Replace examplebucket with the actual bucket name.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Download the object to the specified local path. If a file that has the same name already exists in the path, the downloaded object overwrites the file. If no file that has the same name exists in the path, the downloaded object is saved in the path.
// If you do not specify a local path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs.
// Specify the full path of the object that you want to download from the bucket. Example: exampledir/exampleobject.txt. Then, specify the full path of the local file in which you want to store the downloaded object. Example: D:\\localpath\\examplefile.txt. Do not include the bucket name in the full path.
objectName := "exampledir/exampleobject.txt"
localFilePath := "D:\\localpath\\examplefile.txt"
err = bucket.GetObjectToFile(objectName, localFilePath)
if err != nil {
log.Fatalf("Failed to download file: %v", err)
}
log.Println("File downloaded successfully.")
}
OSSGetObjectRequest * request = [OSSGetObjectRequest new];
// Specify the name of the bucket. Example: examplebucket.
request.bucketName = @"examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
request.objectKey = @"exampledir/exampleobject.txt";
// Configure optional fields.
request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
// Specify the number of bytes that are being downloaded, the number of bytes that are downloaded, and the total number of bytes that you want to download.
NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
};
// request.range = [[OSSRange alloc] initWithStart:0 withEnd:99]; // bytes=0-99. Specify that the download range is from byte 0 to byte 99.
// request.downloadToFileURL = [NSURL fileURLWithPath:@"<filepath>"]; // If you need to directly download the object to a file, specify the path of the file.
OSSTask * getTask = [client getObject:request];
[getTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"download object success!");
OSSGetObjectResult * getResult = task.result;
NSLog(@"download result: %@", getResult.downloadedData);
} else {
NSLog(@"download object failed, error: %@" ,task.error);
}
return nil;
}];
// [getTask waitUntilFinished];
// [request cancel];
#include <alibabacloud/oss/OssClient.h>
#include <memory>
#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. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Download the object as a local file named examplefile.txt and save the file to D:\\localpath. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. */
/* If you do not specify the path of the local file, the downloaded object is saved to the path of the project to which the sample program belongs. */
std::string FileNametoSave = "D:\\localpath\\examplefile.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);
/* Download the object as a local file. */
GetObjectRequest request(BucketName, ObjectName);
request.setResponseStreamFactory([=]() {return std::make_shared<std::fstream>(FileNametoSave, std::ios_base::out | std::ios_base::in | std::ios_base::trunc| std::ios_base::binary); });
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "GetObjectToFile success" << outcome.result().Metadata().ContentLength() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "GetObjectToFile 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;
}
#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;
/* Specify 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_string_t file;
aos_table_t *params;
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_str_set(&file, local_filename);
params = aos_table_make(pool, 0);
/* Download the object to your local file. If a file with the same name already exists, the downloaded object overwrites the file. Otherwise, a new file is created. */
resp_status = oss_get_object_to_file(oss_client_options, &bucket, &object, headers, params, &file, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("Get object from file succeeded\n");
} else {
printf("Get object from file failed\n");
}
/* Release the memory pool. This operation releases memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
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')
# Download the object to your local computer.
bucket.get_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')
Use ossutil
You can use ossutil to download objects. For more information about its installation, see Install ossutil.
The following example demonstrates how to download exampleobject
stored within examplebucket
.
ossutil api get-object --bucket examplebucket --key exampleobject
For more information, see get-object.
Related API operation
The methods described above are fundamentally implemented based on the RESTful API, which you can directly call if your business requires a high level of customization. To directly call an API, you must include the signature calculation in your code. For more information, see GetObject.
Permissions description
By default, an Alibaba Cloud account possesses all permissions. In contrast, RAM users and RAM roles associated with an Alibaba Cloud account have no permissions initially. To grant operational permissions, the Alibaba Cloud account or its administrator must assign them through a RAM policy or a bucket policy.
API | Action | Description |
GetObject |
| Download an object. |
| When downloading an object, if the version of the object is specified by versionId, you need to grant permissions for this operation. |
Billable items
The following table describes the billable items of simple downloads. For information about OSS pricing, see Pricing.
API | Billable item | Description |
GetObject | GET requests | You are charged request fees based on the number of successful requests. |
Outbound traffic over the Internet | If you call the GetObject operation by using a public endpoint, such as oss-cn-hangzhou.aliyuncs.com, or an acceleration endpoint, such as oss-accelerate.aliyuncs.com, you are charged fees for outbound traffic over the Internet based on the data size. | |
Retrieval of IA objects | If IA objects are retrieved, you are charged IA data retrieval fees based on the size of retrieved IA objects. | |
Retrieval of Archive objects in a bucket for which real-time access is enabled | If Archive objects in a bucket for which real-time access is enabled are retrieved, You are charged Archive data retrieval fees based on the size of retrieved Archive objects. | |
Transfer acceleration | If you enable transfer acceleration and use an acceleration endpoint to access your bucket, you are charged transfer acceleration fees based on the data size. |
References
For more information about how to download an object from a versioning-enabled bucket, see Manage objects in a versioning-enabled bucket.
For more information about how to download an object from a versioning-suspended bucket, see Manage objects in a versioning-suspended bucket.
OSS allows you to configure access control lists (ACLs) for buckets and objects. This way, unauthorized third-party users cannot download data from your bucket. For more information, see Access control.
If you want to continue interrupted download tasks from where they are interrupted when you download large objects, you can use resumable download. For more information, see Resumable download.
If you want to grant third-party users the permissions to download objects from your bucket whose ACL is private, use Security Token Service (STS) to generate temporary access credentials or use signed URLs. For more information, see Authorize third-party users to download objects.
If you want an object to be downloaded when specific conditions are met, and you want the object not to be downloaded and an error message is returned when specific conditions are not met, you can specify conditions when you download the object. For more information, see Conditional download.