Simply download OSS files
prerequisite
Files uploaded to OSS。 See Upload file 。 If you want to download Object, Please ensure that the Object Has entered the unfreezing state or Bucket Archive direct reading is enabled. See thaw Object and Archive direct reading 。 If you want to download cold archive storage or deep cold archive storage type Object, Please ensure that the Object It has entered the unfreezing state. See thaw Object 。
Operation mode
use OSS Console
Sign in OSS Management Console 。 single click Bucket List , and then click Target Bucket name. In the left navigation bar, select file management > File List 。 Download the file. Download a single file Method 1: Select the > download 。 explain If you have changed the operation item from the default Collect more Move to Common file operations , there is no need to expand The icon can directly view the operation item. Method 2: click the file name of the target file or the details , on the pop-up details Click in panel download 。 Download multiple files Select multiple files and click download . via OSS The console can be downloaded in batches at most one hundred Files.
Use graphical management tools ossbrowser
Using AliCloud SDK
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 { //Endpoint takes East China 1 (Hangzhou) as an example. Please fill in other regions according to the actual situation. String endpoint = " https://oss-cn-hangzhou.aliyuncs.com "; //Get access credentials from environment variables. Before running this code example, make sure that the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET have been set. EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); //Fill in the bucket name, such as examplebucket. String bucketName = "examplebucket"; //Fill in the full path of the object excluding the bucket name, such as testfolder/exampleobject.txt. String objectName = "testfolder/exampleobject.txt"; //Fill in the full path of the object download to the local. String pathName = "D:\\localpath\\examplefile.txt"; //Fill in the bucket region. Take East China 1 (Hangzhou) as an example, and fill in the region as cn hangzhou. String region = "cn-hangzhou"; //Create an OSSClient instance. //When the OSSClient instance is no longer used, the shutdown method is called to release resources. 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 a local file and save it to the specified local path. If the specified local file exists, it will be overwritten. If it does not exist, it will be created. //If no local path is specified, the downloaded file is saved to the corresponding local path of the project to which the sample program belongs by default. 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({ //Yourregion Fill in the bucket region. Take East China 1 (Hangzhou) as an example, and fill in the region as oss cn hangzhou. region: 'yourRegion', //Get access credentials from environment variables. Before running this code example, make sure that the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET have been set. accessKeyId: process.env.OSS_ACCESS_KEY_ID, accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, authorizationV4: true, //Fill in the bucket name. bucket: 'examplebucket' }); async function get () { try { //Fill in the full path of the object and the full path of the local file. Bucket names cannot be included in the full path of the object. //If the specified local file exists, it will be overwritten. If it does not exist, it will be created. //If no local path is specified, the downloaded file is saved to the corresponding local path of the project to which the sample program belongs by default. 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 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({ //YourRegion is the region where the bucket is located. Take East China 1 (Hangzhou) as an example, and fill in the region as oss cn hangzhou. region: "yourRegion", authorizationV4: true, //The temporary access key (AccessKey ID and AccessKey Secret) obtained from the STS service. accessKeyId: "yourAccessKeyId", accessKeySecret: "yourAccessKeySecret", //The security token (SecurityToken) obtained from the STS service. stsToken: "yoursecurityToken", //Fill in the bucket name. bucket: "examplebucket", }); //Configure the response header to automatically download files when accessing through URL, and set the file name after downloading. const filename = "examplefile.txt"; const response = { "content-disposition": `attachment; filename=${encodeURIComponent( filename )}`, }; //Fill in the full path of the object. Bucket names cannot be included in the full path of the object. const url = client.signatureUrl("exampleobject.txt", { response }); console.log(url); </script> </body> </html>
//Construct a download file request. //Fill in the bucket name (for example, examplebucket) and the full path of the object (for example, exampledir/exampleobject. txt). Bucket names cannot be included in the full path of the object. 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()); } } //Store the downloaded file in the specified local path, such as 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]; //Fill in the bucket name, such as examplebucket. request.bucketName = @"examplebucket"; //Fill in the full path of the file, such as exampledir/exampleobject.txt. Bucket names cannot be included in the full path of the object. request.objectKey = @"exampledir/exampleobject.txt"; //Optional field. request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) { //The length of the current download segment, the total length that has been downloaded, and the total length that needs to be downloaded. NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); }; // request.range = [[OSSRange alloc] initWithStart:0 withEnd:99]; // bytes=0-99, Specify the range to download. // request.downloadToFileURL = [NSURL fileURLWithPath:@"<filepath>"]; //If you need to download the file directly, you need to specify the target file address. 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 OSS account information. */ /*YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com 。*/ std::string Endpoint = "yourEndpoint"; /*YourRegion Fill in the region corresponding to the bucket region. Take East China 1 (Hangzhou) as an example, and fill in the region as cn hangzhou. */ std::string Region = "yourRegion"; /*Fill in the bucket name, such as examplebucket. */ std::string BucketName = "examplebucket"; /*Fill in the full path of the object. The full path cannot contain bucket names, such as exampledir/exampleobject.txt. */ std::string ObjectName = "exampledir/exampleobject.txt"; /*Download the object to the local file examplefile.txt and save it to the specified local path (D: localpath). If the specified local file exists, it will be overwritten. If it does not exist, it will be created. */ /*If no local path is specified, the downloaded file is saved to the corresponding local path of the project to which the sample program belongs by default. */ std::string FileNametoSave = "D:\\localpath\\examplefile.txt"; /*Initialize network and other resources. */ InitializeSdk(); ClientConfiguration conf; conf.signatureVersion = SignatureVersionType::V4; /*Get access credentials from environment variables. Before running this code example, make sure that the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET have been set. */ auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>(); OssClient client(Endpoint, credentialsProvider, conf); client.SetRegion(Region); /*Download the object to 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 { /*Exception handling. */ std::cout << "GetObjectToFile fail" << ",code:" << outcome.error().Code() << ",message:" << outcome.error().Message() << ",requestId:" << outcome.error().RequestId() << std::endl; return -1; } /*Release network and other resources. */ ShutdownSdk(); return 0; }
#include "oss_api.h" #include "aos_http_io.h" /*YourEndpoint fills in the endpoint corresponding to the bucket's region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com 。*/ const char *endpoint = "yourEndpoint"; /*Fill in the bucket name, such as examplebucket. */ const char *bucket_name = "examplebucket"; /*Fill in the full path of the object. The full path cannot contain bucket names, such as exampledir/exampleobject.txt. */ const char *object_name = "exampledir/exampleobject.txt"; /*Fill in the full path of the local file. */ const char *local_filename = "yourLocalFilename"; /*YourRegion Fill in the region corresponding to the bucket region. Take East China 1 (Hangzhou) as an example, and fill in the region as cn hangzhou. */ const char *region = "yourRegion"; void init_options(oss_request_options_t *options) { options->config = oss_config_create(options->pool); /*Initialize the aos_string_t type with a string of char * type. */ aos_str_set(&options->config->endpoint, endpoint); /*Get access credentials from environment variables. Before running this code example, make sure that the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET have been set. */ 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")); //The following two additional parameters need to be configured aos_str_set(&options->config->region, region); options->config->signature_version = 4; /*Whether CNAME is used. 0 means not used. */ options->config->is_cname = 0; /*It is used to set network related parameters, such as timeout. */ options->ctl = aos_http_controller_create(options->pool, 0); } int main(int argc, char *argv[]) { /*Call the aos_http_io_initialize method at the program entrance to initialize global resources such as network and memory. */ if (aos_http_io_initialize(NULL, 0) ! = AOSE_OK) { exit(1); } /*The memory pool used for memory management is equivalent to apr_pool_t. In fact, modern codes are in the apr library. */ aos_pool_t *pool; /*Recreate a memory pool. The second parameter is NULL, which means no other memory pool is inherited. */ 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, curl, etc. */ oss_request_options_t *oss_client_options; /*Allocate memory to options in the memory pool. */ oss_client_options = oss_request_options_create(pool); /*Initialize the option oss_client_options of the client. */ init_options(oss_client_options); /*Initialization 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 file. If the specified local file exists, it will be overwritten. If it does not exist, it will be 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"); } /*Releasing the memory pool is equivalent to releasing the memory allocated by each resource during the request process. */ aos_pool_destroy(pool); /*Release previously allocated global resources. */ aos_http_io_deinitialize(); return 0; }
require 'aliyun/oss' client = Aliyun::OSS::Client.new( #Endpoint takes East China 1 (Hangzhou) as an example. Please fill in other regions according to the actual situation. endpoint: ' https://oss-cn-hangzhou.aliyuncs.com ', #Get access credentials from environment variables. Before running this code example, make sure that the environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET have been set. access_key_id: ENV['OSS_ACCESS_KEY_ID'], access_key_secret: ENV['OSS_ACCESS_KEY_SECRET'] ) #Fill in the bucket name, such as examplebucket. bucket = client.get_bucket('examplebucket') #Download the object locally. 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" ) //Defining Global Variables var ( Region string//Storage area BucketName string//The name of the storage space ObjectName string//Object name ) //The init function is used to initialize command line 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() { //Resolve command line 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 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 configuration and set the credential provider and region cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region) //Create OSS client client := oss.NewClient(cfg) //Specify local file path localFile := "download.file" //Assuming that the last modification time of the object is 18:43:02, October 21, 2024, when the UTC filled in is earlier than this time, the IfModifiedSince restrictions will be met and the download behavior will be triggered. date := time.Date(2024, time.October, 21, 18, 43, 2, 0, time.UTC) //Assume that the ETag is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855, then when the ETag filled in is equal to the ETag value of the object, the qualification condition of IfMatch will be met and the download behavior will be triggered. etag := "\"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"" //Create a request to download an object to a local file getRequest := &oss.GetObjectRequest{ Bucket: oss.Ptr(bucketName), //Storage space name Key: oss.Ptr(objectName), //Object Name IfModifiedSince: oss.Ptr(date.Format(http.TimeFormat)), //Specify the IfModifiedSince parameter IfMatch: oss.Ptr(etag), //Specify the IfMatch parameter } //Execute the operation of downloading objects to local files and process the results 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 parameter parser parser = argparse.ArgumentParser(description="get object sample") #Add the command line parameter -- region, which indicates the area where the storage space is located. It is a required parameter parser.add_argument('--region', help='The region in which the bucket is located.', required=True) #Add the command line parameter -- bucket, which represents the name of the storage space. It is a required parameter parser.add_argument('--bucket', help='The name of the bucket.', required=True) #Add a command line parameter -- endpoint, which indicates the domain name that other services can use to access OSS. It is not a required parameter parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS') #Add the command line parameter -- key, which represents the name of the object and is required parser.add_argument('--key', help='The name of the object.', required=True) def main(): #Resolve command line parameters args = parser.parse_args() #Load credential information from environment variables for authentication credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() #Load the default configuration of the SDK and set the credential provider cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider #Set regional information in configuration cfg.region = args.region #If the endpoint parameter is provided, set the endpoint in the configuration if args.endpoint is not None: cfg.endpoint = args.endpoint #Create an OSS client using the configured information client = oss.Client(cfg) #Execute the request to get the object, and specify the storage space name and object name result = client.get_object(oss.GetObjectRequest( bucket=args.bucket, #Specify storage space name key=args.key, #Specify the object key name )) #Output the result information of the obtained object, which is used 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},' ) #============Mode 1: Full read========== with result.body as body_stream: data = body_stream.read() Print (f "File reading completed, 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}") ##============Mode 2: Block reading========== # with result.body as body_stream: # chunk_path = "./get-object-sample-chunks.txt" # total_size = 0 # with open(chunk_path, 'wb') as f: ## Use 256KB block size (the block_size parameter can be adjusted as needed) # for chunk in body_stream.iter_bytes(block_size=256 * 1024): # f.write(chunk) # total_size += len(chunk) #Print (f "Received data block: {len (chunk)} bytes | Cumulative: {total_size} bytes") #Print (f "The file is downloaded and saved to the path {chunk_path}") #When this script is run directly, call the main function if __name__ == "__main__": Main() # Script entry, which calls the main function when the file is directly run
<?php //Introduce automatic loading files to ensure that dependent libraries can be loaded correctly 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], // Bucket Location (required) "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], //Access domain name (optional) "Bucket"=>['help '=>' The name of the bucket ',' required '=>True],//Bucket name (required) "key" => ['help' => 'The name of the object', 'required' => True], //Object name (required) ]; //Convert the parameter description to the long option format required by getopt //":" after each parameter indicates that the parameter requires a value $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); //Resolve command line parameters $options = getopt("", $longopts); //Verify whether the required parameter exists foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; //Get help information for parameters echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); //If the required parameters are missing, exit the program } } //Extract values from parsed parameters $region = $options["region"]; //Bucket region $bucket = $options["bucket"]; //Bucket name $key = $options["key"]; //Object Name //Load credential information in 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 Credential Provider $cfg->setRegion($region); //Set the bucket region if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); //If the access domain name 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 local file path to save $localFilePath = 'path/to/local/file.txt'; //Please replace with the actual file path //Write content to local file file_put_contents( $localFilePath, $result->body->getContents()); //Print the results //Output HTTP status code, request ID and object content printf( 'status code: '. $result ->statusCode. PHP_EOL.//HTTP status code, for example, 200 indicates success 'request id: '. $result ->requestId. PHP_EOL//The request ID is used to debug or trace requests );
Using Command Line Tools ossutil
ossutil api get-object --bucket examplebucket --key exampleobject
relevant API
Permission description
| | |
|
| |
| | |
| |
Billing description
| | |
| | |
| | |
| | |
| | |
| |
Related Documents
How to open version control Bucket Download the file in, see Under version control Object Operation of 。 How to pause version control after Bucket Download the file in, see Pause version control Object Operation of 。 To prevent third parties from unauthorized Bucket Download data from, OSS Provides Bucket and Object Level of access control. For more information, see Permission control 。 If you want to continue downloading the unfinished part from the location where the download was interrupted during the process of downloading large files, you can use breakpoint resume. See Download of breakpoint resume 。 If you want to make private Bucket Of Object It is provided to a third party for download, please go to STS Temporary access credentials or signatures URL To authorize a third party to download files. See Authorize the third party to download 。 If you want to download a file when the limit conditions are met, an error will be returned and the download behavior will not be triggered. You can specify the limit conditions when downloading a file. See Conditional download 。