After you upload objects to a bucket, you can share the URLs of the objects with third parties for downloads or previews.

Use the OSS console

  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 desired bucket.
  3. In the left-side navigation tree, choose Files > Objects.
  4. Obtain the URLs of objects.
    • 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 described in the following table. Then, click Copy File URL. Copy URL
        ParameterDescription
        Validity PeriodIf the ACL of the object that you want to share 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 URL of an object is generated by using HTTPS. To use HTTP to generate a URL for the object, turn off HTTPS.
        Validity PeriodIf the ACL of the objects 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. The URL list is exported as a local file.
  5. Share the URL list file with third parties for previews or downloads.

Use ossbrowser

You can use ossbrowser to perform the same object-level operations that you can perform in the OSS console. You can follow the on-screen instructions in ossbrowser to download objects. For more information about how to use ossbrowser, see Use ossbrowser.

Use OSS SDKs

The following sample code provides examples on how to use OSS SDKs for common programming languages to share an object with third parties for previews and downloads by providing the object URL. For more information about how to use OSS SDKs for other programming languages to share an object with third parties for previews and downloads by providing the object URL, see Overview.

import com.aliyun.oss.*;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.StorageClass;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.*;
import java.net.URL;
import java.util.*;

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. 
        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";
        // Specify the full path of the local file to which you want to download the object. 
        String pathName = "D:\\localpath\\examplefile.txt";


        // 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. 
        // Use the temporary access credentials obtained from STS to create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
        // Do not use the temporary access credentials obtained from STS to create an OSSClient instance. 
        // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // Specify request headers. 
        Map<String, String> headers = new HashMap<String, String>();
        /*// Specify the storage class of the object. 
        headers.put(OSSHeaders.STORAGE_CLASS, StorageClass.Standard.toString());
        // Specify ContentType. 
        headers.put(OSSHeaders.CONTENT_TYPE, "text/txt");*/

        // Specify user metadata. 
        Map<String, String> userMetadata = new HashMap<String, String>();
        /*userMetadata.put("key1","value1");
        userMetadata.put("key2","value2");*/

        URL signedUrl = null;
        try {
            // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);

            // Generate the signed URL. 
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            // Specify the expiration time of the request. 
            request.setExpiration(expiration);

            // Add the headers to the request. 
            request.setHeaders(headers);
            // Specify user metadata. 
            request.setUserMetadata(userMetadata);

            // Specify query parameters. 
            // Map<String, String> queryParam = new HashMap<String, String>();
            // Specify the IP address or CIDR block. 
            // queryParam.put("x-oss-ac-source-ip","192.0.2.0");
            // Specify the number of the digit 1 in the subnet mask. 
            // queryParam.put("x-oss-ac-subnet-mask","32");
            // Specify the ID of the virtual private cloud (VPC). 
            // queryParam.put("x-oss-ac-vpc-id","vpc-12345678");
            // Specify whether the request can be forwarded. 
            // queryParam.put("x-oss-ac-forward-allow","true");
            // request.setQueryParameter(queryParam);

            // Configure single-connection bandwidth throttling, such as 100 KB/s. Unit: bit/s. 
            // request.setTrafficLimit(100 * 1024 * 8);

            // Generate a signed URL that allows HTTP GET requests. 
            signedUrl = ossClient.generatePresignedUrl(request);
            // Display the signed URL. 
            System.out.println("signed url for putObject: " + signedUrl);
        } 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());
        }

        // Use the signed URL to download the object. In this example, HttpClients is used. 
        getObjectWithHttp(signedUrl, pathName, headers, userMetadata);
    }

    public static void getObjectWithHttp(URL signedUrl, String pathName, Map<String, String> headers, Map<String, String> userMetadata) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            HttpGet get = new HttpGet(signedUrl.toString());

            // If you configure header parameters such as user metadata and storage class when a signed URL is generated, you must send these parameters to the server when you call the signed URL to download the object. If the parameters for the signature are inconsistent with those sent to the server, a signature error is reported. 
            for(Map.Entry header: headers.entrySet()){
                get.addHeader(header.getKey().toString(),header.getValue().toString());
            }
            for(Map.Entry meta: userMetadata.entrySet()){
                // If userMeta is used, the x-oss-meta- prefix is added to userMeta. When you use other methods to generate a signed URL for object download, the x-oss-meta- prefix is also added to userMata. 
                get.addHeader("x-oss-meta-"+meta.getKey().toString(), meta.getValue().toString());
            }

            httpClient = HttpClients.createDefault();
            response = httpClient.execute(get);

            System.out.println("Download status code:"+response.getStatusLine().getStatusCode());
            if(response.getStatusLine().getStatusCode() == 200){
                System.out.println("Download the object by using the network library");
            }
            System.out.println(response.toString());

            // Store the object in the disk. 
            saveFileToLocally(response.getEntity().getContent(), pathName);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            response.close();
            httpClient.close();
        }
    }

    public static void saveFileToLocally(InputStream inputStream, String pathName) throws IOException {
        DataInputStream in = null;
        OutputStream out = null;
        try {
            in = new DataInputStream(inputStream);
            out = new DataOutputStream(new FileOutputStream(pathName));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            in.close();
            out.close();
        }
    }
}
<?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 OSS = require('ali-oss');

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 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'
});

// Obtain the signed URL used to download the exampleobject.txt object. By default, if you use the signed URL in a browser to access the object, the object is previewed but not downloaded. 
// Specify the full path of the object. The full path of the object cannot contain the bucket name. 
const url = client.signatureUrl('exampleobject.txt');
console.log(url);

// Obtain the signed URL used to download the exampleobject.txt object, and set the Content-Disposition header to attachment. This way, if you use the signed URL to access the object in a browser, the object is automatically downloaded, and you can specify the name of the downloaded object. 
// To preview the object when you use the signed URL to access the object in a browser, set the Content-Disposition header to inline and use the custom domain name that is mapped to the bucket to access the object. 
const filename = 'ossdemo.txt' // Specify the name of the downloaded object. 
const response = {
  'content-disposition': `attachment; filename=${encodeURIComponent(filename)}`
}
// Specify the full path of the object. The full path of the object cannot contain the bucket name. 
const url = client.signatureUrl('exampleobject.txt', { response });
console.log(url);

// Obtain the signed URL used to upload the exampleobject.txt object and set the validity period of the URL. 
// Specify the full path of the object. The full path of the object cannot contain the bucket name. 
const url = client.signatureUrl('exampleobject.txt', {
  // Specify the validity period of the signed URL. By default, the validity period is 1,800 seconds. 
  expires: 3600, 
  // Set the request method to PUT. By default, the request method is GET. 
  method: 'PUT'  
});
console.log(url);

// Obtain the signed URL used to download the exampleobject.txt object and specify the Content-Type parameter. 
// Specify the full path of the object. The full path of the object cannot contain the bucket name. 
const url = client.signatureUrl('exampleobject.txt', {
  expires: 3600, 
  method: 'PUT',
  'Content-Type': 'text/plain; charset=UTF-8',
});
console.log(url);
# -*- coding: utf-8 -*-
import oss2
import requests

# 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. 
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# If you use STS authorization, specify the temporary AccessKey pair and the security token that you obtained from STS. 
# auth = oss2.StsAuth('yourAccessKeyId', 'yourAccessKeySecret', 'yourToken')

# 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. 
# Specify the name of the bucket. Example: examplebucket. 
bucket = oss2.Bucket(auth, 'yourEndpoint', 'examplebucket')
# Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name. 
object_name = 'exampledir/exampleobject.txt'

# Specify the headers. 
headers = dict()
# Specify the Accept-Encoding parameter. 
headers['Accept-Encoding'] = 'gzip'

# Specify HTTP query parameters. 
params = dict()
# Configure single-connection bandwidth throttling. Unit: bit/s. In this example, the maximum bandwidth is set to 100 Kbit/s. 
# params['x-oss-traffic-limit'] = str(100 * 1024 * 8)
# Specify the IP address or CIDR block. 
# params['x-oss-ac-source-ip'] = "127.0.0.1"
# Specify the number of the digit 1 in the subnet mask. 
# params['x-oss-ac-subnet-mask'] = "32"
# Specify the ID of the virtual private cloud (VPC). 
# params['x-oss-ac-vpc-id'] = "vpc-t4nlw426y44rd3iq4****"
# Specify whether the request can be forwarded. 
# params['x-oss-ac-forward-allow'] = "true"

# Generate a signed URL that is used to download the object. The validity period of the URL is 60 seconds. 
# By default, OSS identifies the forward slashes (/) in the full path of an object as escape characters when the signed URL is generated. Therefore, you cannot directly use the signed URL. 
# Set the slash_safe parameter to True. This way, OSS does not identify the forward slashes (/) in the full path of the object as escape characters. Then, you can directly use the generated signed URL. 
url = bucket.sign_url('GET', object_name, 60, slash_safe=True, headers=headers, params=params)
print('The signed URL:', url)

# Use the signed URL to download the object. requests is used as an example. 
resp = requests.get(url, headers=headers)

# Specify the path of the local file. Example: D:\\exampledir\\examplefile.txt. 
with open("D:\\exampledir\\examplefile.txt", "wb") as code:
    code.write(resp.content)

Use ossutil

For more information about how to perform simple download by using ossutil, see sign (generate signed object URLs).

FAQ

What do I do if garbled characters appear when I preview or download an object by using the object URL whose name contains Chinese characters?

If garbled characters appear when you download the test.txt object to your local computer by using the URL of the object, you must encode the Chinese character contained in the object URL by specifying Content-Disposition in the following format: "attachment;filename="+URLEncoder.encode("test","UTF-8")+".txt;filename*=UTF-8''"+URLEncoder.encode("test","UTF-8")+".txt"). Example:
attachment;filename=%E6%B5%8B%E8%AF%95.txt;filename*=%E6%B5%8B%E8%AF%95.txt