This topic describes how to obtain the URL of a single object or the URLs of multiple objects.

Obtain the URL of a single object

An object whose ACL is public read

If the access control list (ACL) of an object is public read, the object can be accessed by anonymous users. The URL of the object is in the following format: https://BucketName.Endpoint/ObjectName. In the preceding URL, ObjectName is the full path of the object that includes the object prefix and suffix. For more information about the endpoints of each region, see Regions and endpoints.

For example, an object named example.jpg is stored in the example directory of a bucket named examplebucket in the China (Hangzhou) region. The following URLs can be used to access the object:

  • URL for access over the Internet: https://examplebucket.oss-cn-hangzhou.aliyuncs.com/example/example.jpg.
  • URL for access over the internal network (from Elastic Compute Service (ECS) instances that are located in the same region as the object): https://examplebucket.oss-cn-hangzhou-internal.aliyuncs.com/example/example.jpg
Important
  • If you map a custom domain name to a bucket in which the object is stored, the URL of the object in the bucket is in the following format: https://YourDomainName/ObjectName.

    For example, if you map a custom domain name example.com to a bucket named examplebucket in the China (Hangzhou) region and the bucket contains the example.jpg object, the URL of the object is https://example.com/example.jpg.

  • To make sure that an image object is previewed when you access the image object, you must map a custom domain name to your bucket and add a CNAME record. For more information, see Use custom domain names to access OSS resources.

An object whose ACL is private

If the ACL of an object is private, the URL of the object must be signed. The URL of the private object is in the following format: https://BucketName.Endpoint/Object?SignatureParameters. You can use the following methods to obtain the URL of a private object and specify the validity period of the URL:

Use the OSS console

You can obtain the URL of a private object in the Object Storage Service (OSS) console. The validity period of an object URL varies based on the account types. Alibaba Cloud accounts can set the validity period of an object URL to up to 32,400 seconds (9 hours). RAM users and temporary users authorized by Security Token Service (STS) can set the validity period of an object URL to up to 3,600 seconds (1 hour). To set the validity period of an object URL to a greater value, you can use ossutil, ossbrowser, or OSS SDKs.

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket in which the private object is stored.
  3. In the left-side navigation tree, choose Files > Objects.
  4. Obtain the URL of the object.
    • Obtain the URL of a single object.
      1. Click the name of the object that you want to share.
      2. In the View Details panel, configure the parameters. The following table describes the parameters. Then, click Copy File URL. Copy URL
        ParameterDescription
        Validity Period (Seconds)If the access control list (ACL) of the object is private, you must specify a validity period for the URL of the object.

        Valid values: 60 to 32400

        Unit: seconds

        To obtain a URL that has a longer validity period, you can use tools such as ossbrowser, OSS SDKs, and ossutil.

        Custom Domain NameTo ensure that an image object or a web page object is previewed but not downloaded when the object is accessed by third parties, generate the URL of the object by using the custom domain name mapped to the bucket.

        This parameter is available only when a custom domain name is mapped to the bucket. For more information, see Map custom domain names.

        HTTPSBy default, the URL of an object is generated by using HTTPS. To use HTTP to generate a URL for the object, turn off HTTPS.
    • Obtain the URLs of multiple objects at a time
      1. Select the objects that you want to share and click Export URL List. list
      2. In the Export URL List panel, configure the parameters. The following table describes the parameters.
        ParameterDescription
        HTTPSBy default, the URLs of objects are generated by using HTTPS. To use HTTP to generate object URLs, turn off HTTPS.
        Validity PeriodIf the ACL of the objects that you want to share is private, you must specify a validity period for the URLs of the objects.

        Valid values: 60 to 32400

        Unit: seconds

        To obtain URLs that have a longer validity period, we recommend that you use ossutil or ossbrowser.

        Custom Domain NameTo ensure that image objects or web page objects are previewed but not downloaded when the objects are accessed by third parties, generate the URLs of the objects by using the custom domain name mapped to the bucket.

        This parameter is available only when a custom domain name is mapped to the bucket. For more information, see Map custom domain names.

        Accelerate EndpointIf third parties located far from your data centers need to access the shared objects, we recommend that you use the acceleration endpoint of the bucket to generate the URLs of the objects.

        This parameter is available only when transfer acceleration is enabled for the bucket. For more information, see Enable transfer acceleration.

      3. Click OK and export the URL list as a local file.

Use ossbrowser

ossbrowser allows you to perform object management operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to obtain a signed URL. For more information about how to use ossbrowser, see Use ossbrowser.

Use OSS SDKs

The following code provides examples on how to generate a signed URL by using OSS SDKs for common programming languages. For more information about how to generate a signed URL by using OSS SDKs for other programming languages, see Overview.

Note When you use STS to generate a signed URL, you must enter the temporary access credentials obtained from STS. The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. For more information about how to obtain temporary access credentials, see Use temporary credentials provided by STS to access OSS.
import com.aliyun.oss.*;
import java.net.URL;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the security token obtained from STS. 
        String securityToken = "yourSecurityToken";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path. 
        String objectName = "exampleobject.txt";

        // Use the temporary access credentials obtained from STS to create an OSSClient instance. 
        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

        try {
            // Specify the validity period of the signed URL. Unit: milliseconds. 
            Date expiration = new Date(new Date().getTime() + 3600 * 1000);
            // Generate a signed URL that allows HTTP GET requests. Visitors can enter the URL in a browser to access specific OSS resources. 
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            System.out.println(url);
        } 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\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;

// Specify the temporary AccessKey pair obtained from STS. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
$securityToken = "yourSecurityToken";
// 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. 
$endpoint = "yourEndpoint";
// Specify the name of the bucket. 
$bucket= "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. 
$object = "exampleobject.txt";
// Set the validity period of a signed URL to 3,600 seconds. 
$timeout = 3600;
// Generate a signed URL that is used to preview the object and use the custom domain name that is mapped to the bucket to access the object. 
$options= array(
    "response-content-disposition"=>"inline",);
// Generate a signed URL that is used to download the object. 
/*$options = array(
    "response-content-disposition"=>"attachment",
);*/
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
    $signedUrl = $ossClient->signUrl($bucket, $object, $timeout,'GET',$options);

} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");               
const { default: axios } = require("axios");
const fs = require("fs");

const client = new OSS({
  // 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 oss-cn-hangzhou. 
  region: 'yourRegion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});
// Generate a signed URL for the object. 
const url = client.signatureUrl("examplefile.txt");

// Use the signed URL to download the object to your local computer and enter the full path of the object. 
const file = "D:\\localpath\\examplefile.txt";

axios({
  url,
  method: "GET",
})
  .then((r) => {
    fs.writeFile(file, r.data, (err) => {
      if (err) {
        console.log(err);
      }
    });
  })
  .catch((e) => console.log(e));
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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. 
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file to which you want to download the object. Example: D:\\localpath\\examplefile.txt. If the specified local file exists, the object to download replaces the file. If the specified local file does not exist, the downloaded file is saved in the path. 
var downloadFilename = "D:\\localpath\\examplefile.txt";
// Create an OSSClient instance. 
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    var metadata = client.GetObjectMetadata(bucketName, objectName);
    var etag = metadata.ETag;
    // Generate the signed URL. 
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
      {
        // Specify the validity period of the signed URL. Default value: 3600. Unit: seconds. 
        Expiration = DateTime.Now.AddHours(1),
    };
    var uri = client.GeneratePresignedUri(req);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
package main

import (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

func HandleError(err error) {
    fmt.Println("Error:", err)
    os.Exit(-1)
}

func main() {
    // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
    client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret", oss.SecurityToken("yourSecurityToken"))
    if err != nil {
        HandleError(err)
    }

    // Specify the name of the bucket. Example: examplebucket. 
    bucketName := "examplebucket"
    // Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name. 
    objectName := "exampledir/exampleobject.txt"
    // Download the object to the specified path on your local computer. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, the downloaded file is saved in the path. 
    bucket, err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // Generate a signed URL with a specified validity period for downloading the object. In this example, the validity period of the URL is 60 seconds. 
    signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 60)
    if err != nil {
        HandleError(err)
    }
    fmt.Printf("Sign Url:%s\n", signedURL)
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the information about the account that is used to access OSS. */
    /* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    /* 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 name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. */ 
    std::string GetobjectUrlName = "exampledir/exampleobject.txt";

    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* Set the validity period of the signed URL. */
    std::time_t t = std::time(nullptr) + 1200;
    /* Generate the signed URL. */
    auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
    if (genOutcome.isSuccess()) {
        std::cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << std::endl;
    }
    else {
        /* Handle exceptions. */
        std::cout << "GeneratePresignedUrl fail" <<
        ",code:" << genOutcome.error().Code() <<
        ",message:" << genOutcome.error().Message() <<
        ",requestId:" << genOutcome.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";
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
const char *access_key_id = "yourAccessKeyId";
const char *access_key_secret = "yourAccessKeySecret";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify 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);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    aos_str_set(&options->config->access_key_id, access_key_id);
    aos_str_set(&options->config->access_key_secret, access_key_secret);
    /* Specify whether to use CNAME to access OSS. The value of 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure 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 that is 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 *headers = NULL;
    aos_table_t *params = NULL;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_http_request_t *req;
    apr_time_t now;
    char *url_str;
    aos_string_t url;
    int64_t expire_time; 
    int one_hour = 3600;
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    aos_str_set(&file, local_filename);
    expire_time = now / 1000000 + one_hour;
    headers = aos_table_make(pool, 0);
    params = aos_table_make(pool, 0);
    req = aos_http_request_create(pool);
    req->method = HTTP_GET;
    now = apr_time_now(); /* Unit: microseconds */
    expire_time = now / 1000000 + one_hour;
    /* Generate a signed URL. */
    url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
    aos_str_set(&url, url_str);    
    /* Release the memory pool. This operation releases memory resources that are allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Use ossutil

For more information about how to generate a signed URL by using ossutil, see sign (generate signed object URLs).

Obtain the URLs of multiple objects

You can obtain the URLs of multiple objects at a time in the OSS console. For more information, see the "Obtain the URLs of multiple objects at a time" section of Authorize third-party users to download objects.

If you want to use ossutil or OSS SDKs to obtain the URLs of multiple objects at a time, you can perform the following steps:
  1. Obtain the names of the objects by calling the ListObjects (GetBucket) operation.
  2. Continuously use the method to obtain the URL of a single object. For more information, see Obtain the URL of a single object.