file

Simply download OSS files

Simple download refers to using OSS API GetObject Interface to download the uploaded file (Object), which is applicable to the scenario where the download can be completed with one HTTP request interaction.

prerequisite

  • The file has been uploaded to OSS. See Upload file

  • If you want to download an object of archive storage type, make sure that the object has entered the unfrozen state or the bucket has enabled archive direct reading. See Unfreeze Object and Archive direct reading

  • If you want to download an object of cold archive storage or deep cold archive storage type, make sure that the object has entered the unfrozen state. See Unfreeze Object

  • Already has oss:GetObject jurisdiction. See Common examples of RAM policy

Operation steps

Using the OSS Console

explain

Downloading folders (including subdirectories) through the OSS console is not supported. If you need to download folders (including subdirectories), you can use ossbrowser, ossutil, SDK, API and other methods to download them.

  1. Sign in OSS Management Console

  2. single click Bucket List , and then click the target bucket name.

  3. In the left navigation bar, select file management > File List

  4. Download the file.

    • Download a single file

      Method 1: Select the more > 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 more 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 You can download up to 100 files in batches at a time through the OSS console.

Using the graphical management tool ossbrowser

The ossbrowser supports operations at the object level similar to those supported by the console. Please follow the ossbrowser interface instructions to complete the simple download operation. For how to use ossbrowser, see Quickly use ossbrowser

Using the AliCloud SDK

The following is just a simple code example for downloading common SDKs. For code examples of simple downloads of other SDKs, see SDK Introduction

 package com.aliyun.oss.demo; import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; public class Demo { public static void main(String[] args) throws Exception { //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"; //Create an OSSClient instance. OSS ossClient = new OSSClientBuilder().build(endpoint,  credentialsProvider); 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(); } } } }
 <? php if (is_file(__DIR__ . '/../autoload.php')) { require_once __DIR__ . '/../autoload.php'; } if (is_file(__DIR__ . '/../vendor/autoload.php')) { require_once __DIR__ . '/../vendor/autoload.php'; } use OSS\Credentials\EnvironmentVariableCredentialsProvider; use OSS\OssClient; //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. $provider = new EnvironmentVariableCredentialsProvider(); //Fill in the endpoint corresponding to the bucket region. Take East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com  $endpoint = " https://oss-cn-hangzhou.aliyuncs.com "; //Fill in the bucket name, such as examplebucket. $bucket= "examplebucket"; //Fill in the full path of the object excluding the bucket name, such as testfolder/exampleobject.txt. $object = "testfolder/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. $localfile = "D:\\localpath\\examplefile.txt"; $options = array( OssClient::OSS_FILE_DOWNLOAD => $localfile ); //Use try catch to catch exceptions. If an exception is caught, the download failed; If no exception is caught, the download is successful. try{ $config = array( "provider" => $provider, "endpoint" => $endpoint, ); $ossClient = new OssClient($config); $ossClient->getObject($bucket, $object, $options); } catch(OssException $e) { printf(__FUNCTION__ .  ": FAILED\n"); printf($e->getMessage() .  "\n"); return; } print(__FUNCTION__ .  ": OK, please check localfile: 'examplefile.txt'" .  "\n");
 const OSS = require('ali-oss'); const client = new OSS({ //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, //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();
 # -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider #The AccessKey of the AliCloud account has access to all APIs, which is very risky. It is strongly recommended that you create and use a RAM account for API access or daily operation and maintenance. Please log in to the RAM console to create a RAM account. auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider()) #Endpoint takes Hangzhou as an example. Please fill in other regions according to the actual situation. #Fill in the bucket name, such as examplebucket. bucket = oss2.Bucket(auth, ' http://oss-cn-hangzhou.aliyuncs.com ', 'examplebucket') #Fill in the full path of the object. The full path does not include the bucket name, such as testfolder/exampleobject.txt. #Download the object to a local file and save it to the specified local path D:   localpath   examplefile.txt. If the specified local file exists, it will be overwritten. If it does not exist, it will be created. bucket.get_object_to_file('testfolder/exampleobject.txt', 'D:\\localpath\\examplefile.txt')
 <! 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", //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)   { } });
 package main import ( "fmt" "os" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { //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. provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { fmt.Println("Error:", err) os.Exit(-1) } //Create an OSSClient instance. //YourEndpoint fills in the endpoint corresponding to the bucket. Take East China 1 (Hangzhou) as an example, fill in as https://oss-cn-hangzhou.aliyuncs.com  Please fill in other regions according to the actual situation. client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider)) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } //Fill in the bucket name, such as examplebucket. bucket, err := client.Bucket("examplebucket") if err != nil { fmt.Println("Error:", err) os.Exit(-1) } //Download the file to the 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. //Fill in the full path of the object (for example, exampledir/exampleobject. txt) and the full path of the local file (for example, D:   localpath   examplefile. txt). Bucket names cannot be included in the full path of the object. err = bucket.GetObjectToFile("exampledir/exampleobject.txt", "D:\\localpath\\examplefile.txt") if err != nil { fmt.Println("Error:", err) os.Exit(-1) } }
 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*/ /*Fill in the endpoint corresponding to the bucket region. Taking East China 1 (Hangzhou) as an example, the Endpoint is filled in as https://oss-cn-hangzhou.aliyuncs.com 。*/ std::string Endpoint = " https://oss-cn-hangzhou.aliyuncs.com "; /*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; /*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); /*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"; 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")); /*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')

Using the command line tool ossutil

For specific operations of using ossutil to download, see Cp (download file)

Use REST API

If your program has high customization requirements, you can directly initiate REST API requests. To directly initiate a REST API request, you need to manually write code to calculate the signature. For more information, see GetObject

Related Documents

  • For how to download files from a bucket with version control enabled, see Enable operations on objects under version control

  • For how to download files in a bucket where version control is suspended, see Pause the operation of an object under version control

  • To prevent third parties from downloading data from your bucket without authorization, OSS provides bucket and object level access control. For more information, see Overview of Access 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 provide the private bucket object to a third party for downloading, please authorize the third party to download the file through STS temporary access credentials or signature URLs. 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