The following sample code provides examples on how to perform conditional download by using OSS SDK for common programming languages to call GetObject
. For more information about how to perform conditional download by using OSS SDKs for other programming languages, see Overview.
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;
import java.util.Date;
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";
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 {
GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
// For example, an object was last modified at 13:27:04, September 26, 2023. If the specified time is earlier than the last modified time, such as Tue Sep 25 13:27:04 CST 2023, the object meets the If-Modified-Since condition and the object is downloaded.
request.setModifiedSinceConstraint(new Date("Tue Sep 25 13:27:04 CST 2023"));
// Download the object to your local device.
ossClient.getObject(request, 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
<?php
// Import the autoload file to ensure that dependency libraries are correctly loaded
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define description information for command line parameters
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located (required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint (optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name (required)
"key" => ['help' => 'The name of the object', 'required' => True], // The object name (required)
];
// Convert parameter descriptions to the long option format required by getopt
// Add ":" after each parameter to indicate that the parameter requires a value
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse command line parameters
$options = getopt("", $longopts);
// Verify that required parameters exist
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Get the help information for the parameter
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // Exit the program if a required parameter is missing
}
}
// Extract values from the parsed parameters
$region = $options["region"]; // The region where the bucket is located
$bucket = $options["bucket"]; // The bucket name
$key = $options["key"]; // The object name
// Load credential information from environment variables
// Use EnvironmentVariableCredentialsProvider to read Access Key ID and Access Key Secret from environment variables
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region where the bucket is located
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Set the endpoint if provided
}
// Create an OSS client instance
$client = new Oss\Client($cfg);
// If the object was, 2024, 18:43:02, the IfModifiedSince condition will be met and the download will be triggered when the specified UTC time is earlier than this time
$ifModifiedSince = "Sun, 21 Oct 2024 18:43:02 GMT";
// If the ETag is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855, the IfMatch condition will be met and the download will be triggered when the specified ETag equals the object's ETag value
$etag = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
// Create a GetObjectRequest object to obtain the content of the specified object
$request = new Oss\Models\GetObjectRequest(
bucket: $bucket,
key: $key,
ifModifiedSince: $ifModifiedSince,
ifMatch: $etag);
// Execute the get object operation
$result = $client->getObject($request);
// Print the result
// Output the HTTP status code, request ID, and object content
printf(
'status code:' . $result->statusCode . PHP_EOL . // HTTP status code, such as 200 for success
'request id:' . $result->requestId . PHP_EOL . // Request ID, used for debugging or tracking requests
'object content:' . $result->body->getContents() . PHP_EOL // The content of the object
);
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,
// Specify the name of the bucket.
bucket: 'examplebucket'
});
async function main() {
try {
// Upload an object named exampleobject.txt.
await client.put("exampleobject.txt", Buffer.from("contenttest"));
// Set the If-Modified-Since header in the request. If the value of this header is earlier than the time when the uploaded object is last modified, the object is downloaded.
let result = await client.get("exampleobject.txt", {
headers: {
"If-Modified-Since": new Date("1970-01-01").toGMTString(),
},
});
console.log(result.content.toString() === "contenttest");
console.log(result.res.status === 200);
// If the value of the If-Modified-Since header is equal to or later than the time when the uploaded object is last modified, OSS returns 304 Not Modified.
result = await client.get("exampleobject.txt", {
headers: {
"If-Modified-Since": new Date().toGMTString(),
},
});
console.log(result.content.toString() === "");
console.log(result.res.status === 304);
} catch (e) {
console.log(e.code === "Not Modified");
}
}
main();
Python
import argparse
import alibabacloud_oss_v2 as oss
from datetime import datetime, timezone
# Create a command-line argument parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="get object to file sample")
# Add the --region argument to specify the region in which the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket argument to specify the bucket in which the object is stored. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint argument to specify the endpoint for accessing OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --file_path argument to specify the local path to save the downloaded content. This argument is required.
parser.add_argument('--file_path', help='The path of the file to save the downloaded content.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# From the environment variables, load the authentication information required to access OSS.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration and specify the credential provider
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region to the provided one.
cfg.region = args.region
# If an endpoint is provided, update the endpoint attribute with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configuration to initialize an OSSClient instance.
client = oss.Client(cfg)
# Define a if_modified_since time condition.
# The object will be downloaded only if the object was last modified later than the specified if_modified_since time condition.
if_modified_since = datetime(2024, 10, 1, 12, 0, 0, tzinfo=timezone.utc)
# Assume that the ETag is DA5223EFCD7E0353BE08866700000000.
etag = "\"DA5223EFCD7E0353BE08866700000000\""
# Execute the request to get the object and save it as a local file.
result = client.get_object_to_file(
oss.GetObjectRequest(
bucket=args.bucket, # Specify the bucket name.
key=args.key, # Specify the object key.
if_modified_since=if_modified_since, # Download the object only if it was last modified earlier than the specified time.
if_match=etag, # Download the object only if its ETag matches the ETag specified here.
),
args.file_path # Specify the local path to save the downloaded file.
)
# Display the response information, such as the status code and request ID.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content length: {result.content_length},'
f' content range: {result.content_range},'
f' content type: {result.content_type},'
f' etag: {result.etag},'
f' last modified: {result.last_modified},'
f' content md5: {result.content_md5},'
f' cache control: {result.cache_control},'
f' content disposition: {result.content_disposition},'
f' content encoding: {result.content_encoding},'
f' expires: {result.expires},'
f' hash crc64: {result.hash_crc64},'
f' storage class: {result.storage_class},'
f' object type: {result.object_type},'
f' version id: {result.version_id},'
f' tagging count: {result.tagging_count},'
f' server side encryption: {result.server_side_encryption},'
f' server side data encryption: {result.server_side_data_encryption},'
f' next append position: {result.next_append_position},'
f' expiration: {result.expiration},'
f' restore: {result.restore},'
f' process status: {result.process_status},'
f' delete marker: {result.delete_marker},'
f' server time: {result.headers.get("x-oss-server-time")},'
)
# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
main() # The entry point. The control flow starts here.
Browser.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<button id='upload'>Upload</button>
<button id='download'>Download</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 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. Example: examplebucket.
bucket: "examplebucket",
});
const download = document.getElementById('download')
const upload = document.getElementById('upload')
// Upload the object.
upload.addEventListener('click', () => {
// Specify the content of the object to upload.
const file = new Blob(['examplecontent'])
// Specify the full path of the object. Example: exampledir/exampleobject.txt.
const fileName = 'exampledir/exampleobject.txt'
const result = client.put(fileName, file).then(r => console.log(r))
})
// Download the object.
download.addEventListener('click', () => {
// Specify the data range of the object to download.
const start = 1, end = 5
client.get('exampledir/exampleobject.txt', {
headers: {
// Set the If-Modified-Since header in the request. If the value of this header is earlier than the time when the uploaded object is last modified, the object is downloaded. // If the value of the If-Modified-Since header is equal to or later than the time when the uploaded object is last modified, OSS returns 304 Not Modified.
"If-Modified-Since": new Date("1970-01-01").toGMTString()
// Set the If-Unmodified-Since header in the request. If the value of this header is equal to or later than the time when the uploaded object is last modified, the object is downloaded. If the value of the If-Unmodified-Since header is earlier than the time when the uploaded object is last modified, OSS returns 412 Precondition Failed.
//"If-Unmodified-Since": new Date(1970-01-01).toGMTString()
// Set the If-Match header to an ETag value. If the specified ETag value matches the ETag of the object, the object is downloaded. If the specified ETag value does not match the ETag of the object, OSS returns 412 Precondition Failed.
//"If-Match": '5B3C1A2E0563E1B002CC607C****'
// Set the If-Match header to an ETag value. If the specified ETag value does not match the ETag of the object, the object is downloaded. If the specified ETag value matches the ETag of the object, OSS returns 304 Not Modified.
//"If-None-Match": '5B3C1A2E0563E1B002CC607C****'
},
}).then(r => {
if (r.content.length > 0) {
const newBlob = new Blob([r.content], { type: r.res.headers['content-type'] });
const link = document.createElement('a')
link.href = window.URL.createObjectURL(newBlob)
link.download = 'foo.txt'
link.click()
window.URL.revokeObjectURL(link.href)
} else {
console.log ('Error code', r.res.status)
console.log ('No eligible objects to download')
}
})
})
</script>
</body>
</html>
Android
// Specify the name of the bucket and the full path of the object. In this example, the name of the bucket 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.
String bucketName = "examplebucket";
String objectKey = "exampledir/exampleobject.txt";
// Construct a request to download the object.
Map<String, String> headers = new HashMap<>();
// If the specified time is earlier than the time when the object was last modified, the object can be downloaded. Otherwise, 304 Not modified is returned.
headers.put(OSSHeaders.GET_OBJECT_IF_MODIFIED_SINCE, "Fri, 13 Nov 2015 14:47:53 GMT");
// If the specified time is later than or equal to the time when the object was last modified, the object can be downloaded. Otherwise, 412 Precondition failed is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_UNMODIFIED_SINCE, "Fri, 13 Nov 2015 14:47:53 GMT");
// If the specified ETag matches that of the object, the object can be downloaded. Otherwise, 412 Precondition failed is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_MATCH, "5B3C1A2E0563E1B002CC607C*****");
// If the specified ETag does not match that of the object, the object can be downloaded. Otherwise, 304 Not modified is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_NONE_MATCH, "5B3C1A2E0563E1B002CC607C*****");
GetObjectRequest get = new GetObjectRequest(bucketName, objectKey);
get.setRequestHeaders(headers);
OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
@Override
public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// The request is successful.
InputStream inputStream = result.getObjectContent();
byte[] buffer = new byte[2048];
int len;
try {
while ((len = inputStream.read(buffer)) != -1) {
// Process the downloaded data.
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(GetObjectRequest 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());
}
}
});
Go
package main
import (
"context"
"flag"
"log"
"net/http"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define 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.
)
// Use the init function to initialize 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 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 OSS client.
client := oss.NewClient(cfg)
// Specify the path of the local file.
localFile := "download.file"
// For example, an object was last modified at 18:43:02, November 21, 2023. If the time specified in the IfModifiedSince condition is earlier than the last modified time, the object is downloaded.
date := time.Date(2024, time.October, 21, 18, 43, 2, 0, time.UTC)
// Assume that the ETag of an object is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. If the ETag specified in the IfMatch condition matches the ETag of the object, the object is downloaded.
etag := "\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\""
// Create a request to download the object.
getRequest := &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
IfModifiedSince: oss.Ptr(date.Format(http.TimeFormat)), // Specify the IfModifiedSince condition.
IfMatch: oss.Ptr(etag), // Specify the IfMatch condition.
}
// Download the object to a local device and process the result.
result, err := client.GetObjectToFile(context.TODO(), getRequest, localFile)
if err != nil {
log.Fatalf("failed to get object to file %v", err)
}
log.Printf("get object to file result:%#v\n", result)
}
iOS
OSSGetObjectRequest *get = [OSSGetObjectRequest new];
// Specify the name of the bucket. For more information about bucket naming, see Bucket naming conventions.
get.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path of the object. For more information about the naming conventions for objects, see Object naming conventions.
get.objectKey = @"exampledir/exampleobject.txt";
NSMutableDictionary *headerFields = [NSMutableDictionary dictionary];
// Set If-Modified-Since to Fri, 13 Oct 2021 14:47:53 GMT.
[headerFields setValue:@"Fri, 13 Oct 2021 14:47:53 GMT" forKey:@"If-Modified-Since"];
// Specify that the object is downloaded only when its last modified time is the specified time or earlier.
[headerFields setValue:[[NSDate new] oss_asStringValue] forKey:@"If-Unmodified-Since"];
// Specify that the object is downloaded only if its entity tag (ETag) is not the specified ETag.
[headerFields setValue:@"5B3C1A2E0563E1B002CC607C****" forKey:@"If-None-Match"];
// Specify that the object is downloaded only if its ETag is the same as the specified ETag.
[headerFields setValue:@"fba9dede5f27731c9771645a3986****" forKey:@"If-Match"];
get.headerFields = headerFields;
[[[client getObject:get] continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
if (!task.error) {
NSLog(@"get object success!");
} else {
NSLog(@"get object error: %@", task.error);
}
return nil;
}] waitUntilFinished];