All Products
Search
Document Center

Object Storage Service:Share objects with object URLs

Last Updated:Jun 24, 2024

By default, the access control list (ACL) of an object in an Object Storage Service (OSS) bucket is private and only the object owner has access to the object. However, the object owner can share the object with third-party users by creating a signed URL based on the access credentials. Third-party users can use the signed URL to download or preview the object within the specified period of time.

Usage notes

  • When you use an OSS SDK to generate a signed URL, the OSS SDK uses a specific algorithm and the key information stored in the local computer to calculate a signature and adds the signature to a URL to ensure the validity and security of the URL. The operations performed to calculate the signature and construct the URL are completed on the client. You do not need to send requests to the server over the network. Therefore, you do not have to be granted specific permissions to generate a signed URL. However, to prevent third-party users from being unable to perform the operation authorized by the signed URL, you must have the corresponding permission to perform the operation.

    For example, if you want to generate a signed URL for an object download or preview, you must have the oss:GetObject permission.

  • To make sure that an object is previewed when you access it, you must map a custom domain name to the bucket that stores the object and add a CNAME record. For more information, see Map a custom domain name to the default domain name of a bucket.

  • When you generate a URL of a private object, you must specify a validity period for the URL. After the validity period ends, you cannot use the URL to access the object. You can create a URL for the object again to maintain URL-based access to the object.

Genera the URL of a single object

Generate the URL of a private object

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

The maximum validity period of an object URL varies based on the account type. For example, you can use an Alibaba Cloud account to set the validity period of an object URL to up to 32,400 seconds (9 hours) or use a RAM user or temporary access credentials obtained from Security Token Service (STS) to set the validity period of an object URL to up to 3,600 seconds (1 hour) in the OSS console. To specify a longer validity period for an object URL, you can use ossutil, ossbrowser, or OSS SDKs. For more information, see Can I set the URL of a private object to not expire?

Use the OSS console

You can generate the URL of a private object in 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 bucket in which the object is stored.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. Generate a URL of the object.

    1. Click the name of the object.

    2. In the View Details panel, configure the parameters described in the following table. Then, click Copy Object URL.复制URL

      Parameter

      Description

      Validity Period

      You must specify a validity period to generate a URL of a private object.

      Valid values: 60 to 32400.

      Unit: seconds.

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

      Custom Domain Name

      If the object is an image or website page and you want to ensure that the object is previewed but not downloaded when it is accessed by using a URL, use the custom domain name that is mapped to the bucket when you create the URL.

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

      Use HTTPS

      By default, the generated URL uses the HTTPS protocol. To generate a URL that uses the HTTP protocol, turn off Use HTTPS.

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 generate a signed URL. For more information, see Use ossbrowser.

Use OSS SDKs

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

Java

  1. Generate a signed URL used to download an object.

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.model.GeneratePresignedUrlRequest;
    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";
            // 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. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
    
            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);
    
                // Create a request to generate a signed URL. 
                GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
                // Set the validity period of the signed URL. 
                request.setExpiration(expiration);
    
                // Generate the signed URL that allows HTTP GET requests. 
                signedUrl = ossClient.generatePresignedUrl(request);
                // Display the signed URL. 
                System.out.println("signed url for getObject: " + 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());
            }
        }
    }
  2. Use the signed URL to download the object.

    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.util.*;
    
    public class Get1 {
        public static void main(String[] args) throws Throwable {        
            // Specify the full path of the local file to which you want to download the object. 
            String pathName = "D:\\example.jpg";
            // Enter the signed URL generated in Step 1. 
            String signedUrl= "yourSignedUrl";
    
            Map<String, String> headers = new HashMap<String, String>();
            Map<String, String> userMetadata = new HashMap<String, String>();
    
            // Use the signed URL to download the object. In this example, HttpClients is used. 
            getObjectWithHttp(signedUrl, pathName, headers, userMetadata);
        }
    
        public static void getObjectWithHttp(String 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);
    
                // If headers, such as metadata headers and the header that indicates the storage class, are specified during URL generation, you must send these headers to the server when you use the signed URL to download the object. If headers that are sent to the server for the signature calculation are inconsistent with those specified during URL generation, 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 userMeta. 
                    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("The object is downloaded by using the network library");
                }
                System.out.println(response.toString());
    
                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

  1. Generate a signed URL used to download an object.

    <?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;
    use OSS\Core\OssException;
    use OSS\Http\RequestCore;
    use OSS\Http\ResponseCore;
     
    // 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. 
    $provider = new EnvironmentVariableCredentialsProvider();
    // 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 = "https://oss-cn-hangzhou.aliyuncs.com";
    // Specify the name of the bucket. Example: examplebucket. 
    $bucket= "examplebucket";
    // Specify the full path of the object. Do not include the bucket name in the full path of the object. 
    $object = "exampleobject.txt";
    // Set the validity period of the signed URL to 3,600 seconds. 
    $timeout = 3600;
    // Generate a signed URL that is used to download the object. 
    $options = array(
        "response-content-disposition"=>"attachment",
    );
    try {
        $config = array(
            "provider" => $provider,
            "endpoint" => $endpoint,        
        );
        $ossClient = new OssClient($config);
        $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");
  2. Use the signed URL to download the object.

    <?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\Http\RequestCore;
    use OSS\Http\ResponseCore;
    // Enter the signed URL generated in Step 1. 
    $signedUrl = 'yourSignedUrl';
    // Specify the full path of the local file to which you want to download the object. 
    $localfile = "D://example.txt";
    // Use the signed URL to download the object. 
    $request = new RequestCore($signedUrl);
    // Set the default method that is used to access the signed URL to GET. 
    $request->set_method('GET');
    $request->add_header('Content-Type', '');
    $request->send_request();
    $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
    if ($res->isOK()) {
        print(__FUNCTION__ . ": OK" . "\n");
    	 file_put_contents($localfile,$request->get_response_body());
    } else {
        print(__FUNCTION__ . ": FAILED" . "\n");
    };   

Node.js

  1. Generate a signed URL used to download an object.

    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: "oss-cn-hangzhou",
      // 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. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
      // Specify the name of the bucket. Example: examplebucket. 
      bucket: "examplebucket",
    });
    // Generate a signed URL used to download the object. 
    const url = client.signatureUrl("exampleobject.txt");
    console.log(url);
  2. Use the signed URL to download the object.

    const axios = require("axios");
    const fs = require("fs");
    // Enter the signed URL generated in Step 1. 
    const url = "yourSignedUrl";
    // Specify the full path of the local file to which you want to download the object. 
    const file = "D://example.txt";
    
    axios
      // Set the response type to arraybuffer. 
      .get(url, { responseType: "arraybuffer" }) 
      .then((response) => {
        fs.writeFile(file, response.data, (err) => {
          if (err) {
            console.log(err);
          } else {
            console.log("The object is downloaded.");
          }
        });
      })
      .catch((error) => {
        console.log(error);
      });

Python

  1. Generate a signed URL used to download an object.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    import requests
    
    # 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. 
    auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
    
    # 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, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
    # Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
    object_name = 'exampleobject.txt'
    
    # Set the validity period of the signed URL to 3,600 seconds. 
    # Set the slash_safe parameter to True to prevent OSS from identifying the forward slashes (/) in the full path of the object as escape characters. This allows you to use the generated signed URL to download the object. 
    url = bucket.sign_url('GET', object_name, 3600, slash_safe=True)
    print('The signed URL:', url) 
  2. Use the signed URL to download the object.

    # -*- coding: utf-8 -*-
    import oss2
    import requests
    # Enter the signed URL generated in Step 1. 
    url = 'yourSignedUrl'
    
    # Use the signed URL to download the object. In this example, the requests module is used. 
    resp = requests.get(url)
    
    # Specify the local path to which you want to download the object. 
    with open("D:\\examplefile.txt", "wb") as code:
        code.write(resp.content)

Browser.js

  1. Generate a signed URL used to download an object.

    const OSS = require("ali-oss");
    const STS = require("ali-oss").STS;
    // const cors = require("cors");
    
    const stsClient = new STS({
      // 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. 
      accessKeyId: process.env.OSS_ACCESS_KEY_ID,
      accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
    });
    // Specify the name of the bucket. Example: examplebucket. 
    const bucket = "examplebucket";
    // 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. 
    const region = "oss-cn-hangzhou";
    // Specify the Alibaba Cloud Resource Name (ARN) of the RAM role. 
    const roleArn = "acs:ram::137918634953****:role/ossram";
    const getSts = () => {
      stsClient
        .assumeRole(
          roleArn,
          `{
            "Statement": [
              {
                "Effect": "Allow",
                "Action": "*",
                "Resource": [
                  "acs:oss:*:*:examplebucket/*"
                ]
              }
            ]
          }`,
          3000 // Specify the validity period of the security token. Unit: seconds. 
        )
        .then((r) => {
          console.log("send:", r.credentials);
          const { SecurityToken, AccessKeyId, AccessKeySecret } = r.credentials;
          const client = new OSS({
            bucket,
            region,
            accessKeyId: AccessKeyId,
            accessKeySecret: AccessKeySecret,
            stsToken: SecurityToken,
            refreshSTSTokenInterval: 9000,
          });
          // Generate the signed URL that is used to download the object. 
          const url = client.asyncSignatureUrl("exampleobject.txt", {
            expires: 3600,
            method: "GET",
          });
          console.log("url:", url);
          // client.get("exampleobject.txt", Buffer.from("body")).then((res) => {
          //   console.log("res", res.url);
          // });
        });
    };
    getSts();
    
  2. Use the signed URL to download the object.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Document</title>
      </head>
      <body>
        <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
        <script>
          // Enter the signed URL generated in Step 1. 
          const url = "yourSignedUrl";
          var xhr = new XMLHttpRequest();
          xhr.open("GET", url, true);
          // Set the response type to blob. 
          xhr.responseType = "blob"; 
          xhr.onload = function () {
            if (xhr.status === 200) {
              const blob = xhr.response;
              const reader = new FileReader();
              reader.onloadend = function () {
                const fileData = reader.result;
                // Specify the name of the downloaded object. 
                const file = new File([fileData], "examplefile.txt");
                const a = document.createElement("a");
                a.href = URL.createObjectURL(file);
                a.download = file.name;
                a.click();
              };
              reader.readAsArrayBuffer(blob);
            } else {
              console.log("The request failed.");
            }
          };
          xhr.send();
        </script>
      </body>
    </html>

Android

  1. Generate a signed URL used to download an object.

    // 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: exampleobject.txt. 
    String objectKey = "exampleobject.txt";
    String url = null;
    try {
        // Generate a signed URL to download the object. 
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
        // Set the validity period of the signed URL to 30 minutes. 
        request.setExpiration(30*60);
        request.setMethod(HttpMethod.GET);
        url = oss.presignConstrainedObjectURL(request);
        Log.d("url", url);
    } catch (ClientException e) {
        e.printStackTrace();
    }
  2. Use the signed URL to download the object.

    // Enter the generated signed URL. 
    String url = "";
    OkHttpClient client = new OkHttpClient();
    // Use the signed URL to download an object. 
    Request getRequest = new Request.Builder()
            .url(url)
            .get()
            .build();
    client.newCall(getRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.code() == 203 || response.code() >= 300) {
                Log.d("download", "fail");
                Log.d("download", response.body().string());
                return;
            }
            // The object is downloaded. 
            InputStream inputStream = response.body().byteStream();
    
            byte[] buffer = new byte[2048];
            int len;
    
            while ((len = inputStream.read(buffer)) != -1) {
                // Process the downloaded data. For example, display the image or perform a write operation on the object. 
            }
        }
    });

Go

  1. Generate a signed URL used to download an object.

    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() {
        // 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. 
        provider, err := oss.NewEnvironmentVariableCredentialsProvider()
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
        // Create an OSSClient instance. 
        // 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 your actual endpoint. 
        client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
        if err != nil {
            fmt.Println("Error:", err)
            os.Exit(-1)
        }
    
        // Specify the name of the bucket. Example: examplebucket. 
        bucketName := "examplebucket"
        // Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. 
        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 path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. 
        bucket, err := client.Bucket(bucketName)
        if err != nil {
            HandleError(err)
        }
    
        // Generate a signed URL that has a specific 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)
    }
  2. Use the signed URL to download the object.

    package main
    
    import (
    	"fmt"
    	"os"
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
        // Create an OSSClient instance. 
        // 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 your actual endpoint. 
    	client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	
      	// Specify the name of the bucket. Example: examplebucket. 
      	bucketName := "examplebucket"
      	// Specify the full path of the local file to which you want to download the object. 
      	localDownloadedFilename := "D://example.txt"
      
      	bucket, err := client.Bucket(bucketName)
      	if err != nil {
        	HandleError(err)
      	}
      	// Enter the signed URL generated in Step 1. 
      	signedURL := "yourSignedUrl"
      	// Use the generated signed URL to download the object to a local path. 
      	err = bucket.GetObjectToFileWithURL(signedURL, localDownloadedFilename)
      	if err != nil {
        	HandleError(err)
      	}
    }
    
    func HandleError(err error) {
    	fmt.Println("Error:", err)
    	os.Exit(-1)
    }

iOS

  1. Generate a signed URL used to download an object.

    // Specify the name of the bucket. 
    NSString *bucketName = @"examplebucket";
    // Specify the name of the object. 
    NSString *objectKey = @"exampleobject.txt";
    __block NSString *urlString;
    // Generate a signed URL with a specified validity period for downloading the object. In this example, the validity period of the URL is 30 minutes. 
    OSSTask *task = [client presignConstrainURLWithBucketName:bucketName
                                                withObjectKey:objectKey
                                                   httpMethod:@"GET"
                                       withExpirationInterval:30 * 60
                                               withParameters:@{}];
    [task continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
        if (task.error) {
            NSLog(@"presign error: %@", task.error);
        } else {
            urlString = task.result;
            NSLog(@"url: %@", urlString);
        }
        return nil;
    }];
  2. Use the signed URL to download the object.

    // Use the signed URL to download the object. 
    NSURL * url = [NSURL URLWithString:urlString];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"download error: %@", error);
            return;
        } else if (((NSHTTPURLResponse*)response).statusCode == 203 ||
                   ((NSHTTPURLResponse*)response).statusCode >= 300) {
            NSString *body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"download error: %@", body);
            return;
        }
        NSLog(@"download success");
    }];
    [sessionTask resume];

Use ossutil

You can generate a signed URL by using ossutil. For more information, see sign.

Generate the URL of a public-read object

If the 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 name 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 an Elastic Compute Service instance in the same region as the object): https://examplebucket.oss-cn-hangzhou-internal.aliyuncs.com/example/example.jpg.

Note

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 the 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.

Obtain the URLs of multiple objects

You can obtain the URLs of multiple objects at a time in the OSS console.

  1. Select the objects whose URLs you want to obtain and click Export URL List.list

  2. In the Export URL List panel, configure the parameters described in the following table.

    Parameter

    Description

    Use HTTPS

    By default, the generated URLs use the HTTPS protocol. To generate URLs that use the HTTP protocol, turn off Use HTTPS.

    Validity Period

    If the ACLs of the objects are 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 Name

    If the objects are images or website pages and you want to ensure that the objects are previewed but not downloaded when they are accessed by using URLs, use the custom domain name that is mapped to the bucket when you create the URLs.

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

    Accelerate Endpoint

    If 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 if 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.

Note

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 GetBucket (ListObjects) operation.

  2. Repeatedly call the method that is used to obtain the URL of a single object to obtain the URLs of the objects. For more information, see Obtain the URL of a single object.

References

You can upload Elastic Compute Service (ECS) images to OSS and use the URLs of images to import the images. For more information, see Upload image files to OSS and Import custom images.