Una descarga simple utiliza la operación de API GetObject para descargar un objeto mediante una única solicitud HTTP.
Requisitos previos
Los objetos ya se cargaron en OSS. Para obtener más información, consulte Upload objects.
Si desea descargar un objeto de la clase de almacenamiento Archive, asegúrese de que el objeto esté restaurado o de que Archive Direct Read esté habilitado para el bucket. Para obtener más información, consulte Restore objects.
Para descargar un objeto de la clase de almacenamiento Cold Archive o Deep Cold Archive, primero debe restaurarlo. Para obtener más información, consulte Restore objects.
Métodos
Debido a un cambio de política orientado a mejorar el cumplimiento y la seguridad, a partir del 20 de marzo de 2025, los nuevos usuarios de OSS deben use a custom domain name (CNAME) para ejecutar operaciones de API de datos en buckets de OSS ubicados en regiones de China continental. Los endpoints públicos predeterminados están restringidos para estas operaciones. Consulte el anuncio oficial para ver la lista completa de las operaciones afectadas. Si accede a sus datos mediante HTTPS, debe bind a valid SSL Certificate a su dominio personalizado. Esto es obligatorio para acceder a OSS Console, ya que la consola exige HTTPS.
OSS console
No es posible descargar un directorio con sus subdirectorios desde OSS console. Para descargar un directorio, utilice herramientas como ossbrowser, ossutil, un SDK de OSS u operaciones de API.
Inicie sesión en OSS console.
En el panel de navegación izquierdo, haga clic en Buckets. En la página que aparece, haga clic en el nombre del bucket de destino.
En el panel de navegación izquierdo, elija Object Management > Objects.
-
Descargue uno o varios objetos.
-
Descargar un solo objeto
Método 1: en la columna Actions del objeto de destino, elija
> Download.NotaSi movió esta operación de la sección predeterminada Added to More a la sección Common Operations, puede hacer clic directamente en la opción sin expandir el ícono
.Método 2: haga clic en el nombre del objeto de destino o en View Details dentro de la columna Actions. En el panel Detail que aparece, haga clic en Download.
-
Descargar varios objetos
Seleccione varios objetos y haga clic en Download.
-
ossbrowser
ossbrowser admite operaciones a nivel de objeto similares a las disponibles en OSS console. Siga las instrucciones en pantalla del cliente de ossbrowser para realizar una descarga simple. Para obtener más información sobre cómo usar ossbrowser, consulte Common operations.
SDK de OSS
A continuación se proporcionan ejemplos de código para realizar una descarga simple con los SDK de OSS de los lenguajes de programación más comunes. Para obtener información sobre descargas simples con otros SDK de OSS, consulte SDK overview.
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;
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.
// 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 {
// 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();
}
}
}
} 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,
authorizationV4: true,
// 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(); <!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) {
}
});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')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)
}
import argparse
import alibabacloud_oss_v2 as oss
import os
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="get object 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. 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 name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If an endpoint is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the configured information to create an OSS client.
client = oss.Client(cfg)
# Execute a request to get the object. Specify the bucket name and object name.
result = client.get_object(oss.GetObjectRequest(
bucket=args.bucket, # Specify the bucket name.
key=args.key, # Specify the object key.
))
# Print the result of getting the object to check whether the request is successful.
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},'
)
# ========== Method 1: Read the entire object ==========
with result.body as body_stream:
data = body_stream.read()
print(f"The file is read. Data length: {len(data)} bytes")
path = "./get-object-sample.txt"
with open(path, 'wb') as f:
f.write(data)
print(f"The file is downloaded and saved to the path: {path}")
# # ========== Method 2: Read in chunks ==========
# with result.body as body_stream:
# chunk_path = "./get-object-sample-chunks.txt"
# total_size = 0
# with open(chunk_path, 'wb') as f:
# # Use a 256 KB block size. You can change the block_size parameter based on your needs.
# for chunk in body_stream.iter_bytes(block_size=256 * 1024):
# f.write(chunk)
# total_size += len(chunk)
# print(f"Data block received: {len(chunk)} bytes | Total: {total_size} bytes")
# print(f"The file is downloaded and saved to the path: {chunk_path}")
# When this script is run directly, the main function is called.
if __name__ == "__main__":
main() # The entry point of the script. When the file is run directly, the main function is called.<?php
// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description of 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 the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters exist.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information of the parameter.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required parameter is missing, exit the program.
}
}
// 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 the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key 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 credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);
// Execute the get object operation.
$result = $client->getObject($request);
// Define the path of the local file to be saved.
$localFilePath = 'path/to/local/file.txt'; // Replace it with the actual file path.
// Write the content to the local file.
file_put_contents( $localFilePath, $result->body->getContents());
// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
'request id:' . $result->requestId . PHP_EOL // The request ID, which is used for debugging or tracking requests.
);
CLI de ossutil
Puede utilizar la herramienta de línea de comandos ossutil para descargar objetos. Para obtener información sobre cómo instalar ossutil, consulte Install ossutil.
El siguiente comando descarga el objeto exampleobject del bucket examplebucket.
ossutil api get-object --bucket examplebucket --key exampleobject
Para obtener más información sobre este comando, consulte get-object.
Referencia de API
Los métodos descritos en este tema se implementan con base en la operación de API GetObject. Si requiere mayor personalización, llame directamente a la operación de API REST GetObject, lo cual implica calcular la firma manualmente. Para obtener más información, consulte GetObject.
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios o roles de RAM bajo una cuenta de Alibaba Cloud no cuentan con ningún permiso por defecto. La cuenta de Alibaba Cloud o el administrador de la cuenta deben otorgar los permisos de operación mediante RAM policies o Bucket Policy.
|
API |
Action |
Descripción |
|
GetObject |
|
Descarga un objeto. |
|
|
Se requiere este permiso cuando, al descargar un objeto, se especifica la versión del objeto mediante versionId. |
|
|
|
Se requiere este permiso cuando los metadatos del objeto contienen X-Oss-Server-Side-Encryption: KMS durante la descarga. |
Facturación
A continuación se muestran los elementos facturables aplicables a las descargas simples. Para conocer el precio unitario de cada elemento, consulte Precios de Object Storage Service.
|
API |
Elemento facturable |
Descripción |
|
GetObject |
Solicitudes GET |
Se le cobran tarifas de solicitud según la cantidad de solicitudes exitosas. |
|
Tráfico saliente por Internet |
Si llama a la operación GetObject mediante un endpoint público, como oss-cn-hangzhou.aliyuncs.com, o un endpoint de aceleración, como oss-accelerate.aliyuncs.com, se le cobran tarifas por tráfico saliente a través de Internet según el tamaño de los datos. |
|
|
Recuperación de objetos IA |
Si recupera objetos IA, se le cobran tarifas de recuperación de datos IA según el tamaño de los datos recuperados. |
|
|
Recuperación de objetos Archive en un bucket con acceso en tiempo real habilitado |
Si recupera objetos Archive en un bucket con acceso en tiempo real habilitado, se le cobran tarifas de recuperación de datos Archive según el tamaño de los objetos recuperados. |
|
|
Tarifas de aceleración de transferencia |
Si habilita la aceleración de transferencia y usa un endpoint de aceleración para acceder a su bucket, se le cobran tarifas de aceleración de transferencia según el tamaño de los datos. |
Referencias
Para aprender a descargar un objeto de un bucket con control de versiones habilitado, consulte Manage objects in a versioning-enabled bucket.
Para aprender a descargar un objeto de un bucket con control de versiones suspendido, consulte Manage objects in a versioning-suspended bucket.
Para evitar accesos no autorizados y descargas de datos desde sus buckets, OSS ofrece control de acceso a nivel de bucket y de objeto. Para obtener más información, consulte Access control overview.
Para reanudar la descarga interrumpida de un objeto grande, utilice una descarga reanudable. Para obtener más información, consulte Resumable download.
Si necesita autorizar a un tercero para descargar objetos de un bucket privado, utilice credenciales de acceso temporales de STS o una URL firmada. Para obtener más información, consulte Authorize third parties to download objects.
Para descargar un objeto únicamente cuando se cumplen condiciones específicas, utilice una descarga condicional. Para obtener más información, consulte Conditional download.