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
// Introduce autoload files to load dependency libraries
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define and describe command-line parameters
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
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 the required parameters are not configured.
}
}
// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket
$key = $options["key"]; // The name of the object
// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// If the last modified time of the object is October 21, 2024, 18:43:02, and the specified UTC time is earlier than this time, the IfModifiedSince condition is met and the download operation is triggered.
$ifModifiedSince = "Sun, 21 Oct 2024 18:43:02 GMT";
// If the ETag of the object is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855, and the specified ETag is the same as the ETag of the object, the IfMatch condition is met and the download operation is triggered.
$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);
// Query the object.
$result = $client->getObject($request);
// Display the result.
// Output the HTTP status code, request ID, and content of the object.
printf(
'status code:' . $result->statusCode . PHP_EOL . // HTTP status code, such as 200 for success
'request id:' . $result->requestId . PHP_EOL . // Request ID for debugging or tracking requests
'object content:' . $result->body->getContents() . PHP_EOL // Content of the object
);
Node.js
const OSS = require('ali-oss');
const client = new OSS({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourRegion',
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the bucket name.
bucket: 'examplebucket'
});
async function main() {
try {
// Upload a file named exampleobject.txt to the destination bucket. You can customize the file content.
await client.put("exampleobject.txt", Buffer.from("contenttest"));
// Specify a time in the If-Modified-Since request header. The object is downloaded if the specified time is earlier than the actual modification time of the object.
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 specified time is the same as or later than the actual modification time of the object, a 304 Not Modified error is returned.
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: get object and save to file sample.
parser = argparse.ArgumentParser(description="get object to file sample")
# Add the --region command-line 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 command-line argument to specify the name of the bucket from which to get the object. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument to specify the domain name that other services can use to access OSS. This argument is not required.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument to specify the key of the object (file) in OSS. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --file_path command-line argument to specify the local path of the downloaded file. 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 to get the user-input values.
args = parser.parse_args()
# Load the credentials required to access OSS from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configurations of the SDK to create a configuration object and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region property of the configuration object based on the command-line arguments.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint property of the configuration object.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding configurations to initialize the OSS client to interact with OSS.
client = oss.Client(cfg)
# Define the if_modified_since time.
# Only objects modified after this time are returned.
if_modified_since = datetime(2024, 10, 1, 12, 0, 0, tzinfo=timezone.utc)
# Assume that the ETag is DA5223EFCD7E0353BE08866700000000. If the specified ETag is the same as the ETag of the object, the IfMatch condition is met and the download is triggered.
etag = "\"DA5223EFCD7E0353BE08866700000000\""
# Execute the request to get the object and save it to 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, # Only objects modified after the specified time are returned.
if_match=etag, # Only objects with a matching ETag are returned.
),
args.file_path # Specify the local path to which the file is downloaded.
)
# Print the result of getting the object, including 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")},'
)
# When this script is run directly, call the main function to start the processing logic.
if __name__ == "__main__":
main() # The entry point of the script. The program flow starts from 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({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourRegion',
authorizationV4: true,
// The temporary AccessKey ID and AccessKey secret obtained from Security Token Service (STS).
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// The SecurityToken obtained from STS.
stsToken: 'yourSecurityToken',
// Specify the bucket name. For example, examplebucket.
bucket: "examplebucket",
});
const download = document.getElementById('download')
const upload = document.getElementById('upload')
// Upload the file.
upload.addEventListener('click', () => {
// Specify the content of the file to upload.
const file = new Blob(['examplecontent'])
// Specify the full path of the file to upload. For example, exampledir/exampleobject.txt.
const fileName = 'exampledir/exampleobject.txt'
const result = client.put(fileName, file).then(r => console.log(r))
})
// Download the file.
download.addEventListener('click', () => {
// Specify the byte range to download.
const start = 1, end = 5
client.get('exampledir/exampleobject.txt', {
headers: {
// Specify a time in the If-Modified-Since request header. The file is downloaded if the specified time is earlier than the actual modification time of the file. If the specified time is the same as or later than the actual modification time, 304 Not Modified is returned.
"If-Modified-Since": new Date("1970-01-01").toGMTString()
// Specify a time in the If-Unmodified-Since request header. The file is downloaded if the specified time is the same as or later than the actual modification time of the file. If the specified time is earlier than the actual modification time, 412 Precondition Failed is returned.
//"If-Unmodified-Since": new Date(1970-01-01).toGMTString()
// Specify an ETag in the If-Match request header. The file is downloaded if the specified ETag matches the ETag of the file. If the specified ETag does not match, 412 Precondition Failed is returned.
//"If-Match": '5B3C1A2E0563E1B002CC607C****'
// Specify an ETag in the If-None-Match request header. The file is downloaded if the specified ETag does not match the ETag of the file. If the specified ETag matches, 304 Not Modified is returned.
//"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 items to download that meet the conditions')
}
})
})
</script>
</body>
</html>
Android
// Set the bucket name, such as examplebucket, and the full path of the object, such as exampledir/exampleobject.txt.
// The full path of the object cannot contain the bucket name.
String bucketName = "examplebucket";
String objectKey = "exampledir/exampleobject.txt";
// Create a request to download the object.
Map<String, String> headers = new HashMap<>();
// If the specified time is earlier than the object's last modification time, the object is downloaded. Otherwise, a 304 Not modified error is returned.
headers.put(OSSHeaders.GET_OBJECT_IF_MODIFIED_SINCE, "Fri, 13 Nov 2015 14:47:53 GMT");
// If the specified time is the same as or later than the object's last modification time, the object is downloaded. Otherwise, a 412 Precondition failed error is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_UNMODIFIED_SINCE, "Fri, 13 Nov 2015 14:47:53 GMT");
// If the specified ETag matches the object's ETag, the object is downloaded. Otherwise, a 412 Precondition failed error is returned.
// headers.put(OSSHeaders.GET_OBJECT_IF_MATCH, "5B3C1A2E0563E1B002CC607C*****");
// If the specified ETag does not match the object's ETag, the object is downloaded. Otherwise, a 304 Not modified error 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) {
// The request failed.
if (clientExcepion != null) {
// A client exception occurred, such as a network exception.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// A service exception occurred.
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];