Tous les produits
Search
Centre de documentation

Object Storage Service:Télécharger un objet à l'aide d'une URL pré-signée

Dernière mise à jour :Aug 18, 2026

Par défaut, la liste de contrôle d'accès (ACL) d'un objet dans un compartiment Object Storage Service (OSS) est privée. Seul le propriétaire de l'objet dispose des autorisations nécessaires pour y accéder. Utilisez le SDK OSS pour Python afin de générer une URL pré-signée autorisant les requêtes HTTP GET et définissant une durée de validité. Partagez cette URL avec un utilisateur pour lui permettre de télécharger temporairement l'objet. Pendant la période de validité, l'utilisateur peut télécharger l'objet à plusieurs reprises. Une fois cette période écoulée, il doit obtenir une nouvelle URL pré-signée.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et points de terminaison pris en charge, consultez Régions et points de terminaison.

  • Les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour savoir comment configurer les identifiants d'accès, consultez Configurer les identifiants d'accès.

  • Une instance OSSClient est créée à l'aide d'un point de terminaison OSS. Si vous souhaitez créer une instance OSSClient en utilisant des noms de domaine personnalisés ou le Security Token Service (STS), consultez Initialisation.

  • Aucune autorisation n'est requise pour générer une URL pré-signée. Toutefois, pour qu'un tiers puisse télécharger l'objet via cette URL, l'utilisateur qui génère l'URL doit disposer de l'autorisation oss:GetObject. Pour plus d'informations sur l'attribution des autorisations, consultez Accorder des autorisations personnalisées à un utilisateur RAM.

  • Cette rubrique utilise des URL pré-signées V4 avec une durée de validité de sept jours. Pour plus d'informations, consultez (Recommandé) Signatures V4 dans les URL pré-signées.

Processus

Le schéma suivant illustre la procédure de téléchargement d'un objet à l'aide d'une URL pré-signée.

image

Exemple de code

  1. L'exemple de code suivant montre comment générer une URL pré-signée autorisant les requêtes HTTP GET :

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint for 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 ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    
    # Generate a presigned URL that is used to download the object. In this example, the validity period of the URL is 600 seconds.
    # By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the presigned URL cannot be directly used.
    # 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, and the presigned URL can be directly used.
    url = bucket.sign_url('GET', object_name, 600, slash_safe=True)
    print('Presigned URL:', url)
  2. L'exemple de code suivant montre comment utiliser l'URL pré-signée autorisant les requêtes HTTP GET pour télécharger un objet :

    curl

    curl -SO "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"

    Java

    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Demo {
        public static void main(String[] args) {
            // Replace with the generated presigned URL for the GET request.
            String fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
            // Enter the destination path to save the file, including the file name and extension.
            String savePath = "C:/downloads/myfile.txt";
    
            try {
                downloadFile(fileURL, savePath);
                System.out.println("Download completed!");
            } catch (IOException e) {
                System.err.println("Error during download: " + e.getMessage());
            }
        }
    
        private static void downloadFile(String fileURL, String savePath) throws IOException {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
    
            // Check the response code.
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Input stream.
                InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                // Output stream.
                FileOutputStream outputStream = new FileOutputStream(savePath);
    
                byte[] buffer = new byte[4096]; // Buffer.
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
    
                outputStream.close();
                inputStream.close();
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();
        }
    }

    Node.js

    const https = require('https');
    const fs = require('fs');
    
    const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
    const savePath = "C:/downloads/myfile.txt";
    
    https.get(fileURL, (response) => {
        if (response.statusCode === 200) {
            const fileStream = fs.createWriteStream(savePath);
            response.pipe(fileStream);
            
            fileStream.on('finish', () => {
                fileStream.close();
                console.log("Download completed!");
            });
        } else {
            console.error(`Download failed. Server responded with code: ${response.statusCode}`);
        }
    }).on('error', (err) => {
        console.error("Error during download:", err.message);
    });

    Python

    import requests
    
    file_url = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"
    save_path = "C:/downloads/myfile.txt"
    
    try:
        response = requests.get(file_url, stream=True)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(4096):
                    f.write(chunk)
            print("Download completed!")
        else:
            print(f"No file to download. Server replied HTTP code: {response.status_code}")
    except Exception as e:
        print("Error during download:", e)

    Go

    package main
    
    import (
        "io"
        "net/http"
        "os"
    )
    
    func main() {
        fileURL := "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"
        savePath := "C:/downloads/myfile.txt"
    
        response, err := http.Get(fileURL)
        if err != nil {
            panic(err)
        }
        defer response.Body.Close()
    
        if response.StatusCode == http.StatusOK {
            outFile, err := os.Create(savePath)
            if err != nil {
                panic(err)
            }
            defer outFile.Close()
    
            _, err = io.Copy(outFile, response.Body)
            if err != nil {
                panic(err)
            }
            println("Download completed!")
        } else {
            println("No file to download. Server replied HTTP code:", response.StatusCode)
        }
    }

    JavaScript

    const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
    const savePath = "C:/downloads/myfile.txt"; // The file name to use for the download.
    
    fetch(fileURL)
        .then(response => {
            if (!response.ok) {
                throw new Error(`Server replied HTTP code: ${response.status}`);
            }
            return response.blob(); // Convert the response to a blob.
        })
        .then(blob => {
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = savePath; // Set the name of the downloaded file.
            document.body.appendChild(link); // This step ensures that the link exists in the document.
            link.click(); // Simulate a click on the download link.
            link.remove(); // Remove the link after completion.
            console.log("Download completed!");
        })
        .catch(error => {
            console.error("Error during download:", error);
        });

    Android-Java

    import android.os.AsyncTask;
    import android.os.Environment;
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class DownloadTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String fileURL = params[0];
            String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myfile.txt"; // The modified save path.
            try {
                URL url = new URL(fileURL);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setRequestMethod("GET");
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                    FileOutputStream outputStream = new FileOutputStream(savePath);
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    outputStream.close();
                    inputStream.close();
                    return "Download completed!";
                } else {
                    return "No file to download. Server replied HTTP code: " + responseCode;
                }
            } catch (Exception e) {
                return "Error during download: " + e.getMessage();
            }
        }
    }

    Objective-C

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // Define the file URL and save path (change to a valid path).
            NSString *fileURL = @"https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
            NSString *savePath = @"/Users/your_username/Desktop/myfile.txt"; // Replace with your username.
            
            // Create a URL object.
            NSURL *url = [NSURL URLWithString:fileURL];
            
            // Create a download task.
            NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                // Error handling.
                if (error) {
                    NSLog(@"Error during download: %@", error.localizedDescription);
                    return;
                }
                
                // Check the data.
                if (!data) {
                    NSLog(@"No data received.");
                    return;
                }
                
                // Save the file.
                NSError *writeError = nil;
                BOOL success = [data writeToURL:[NSURL fileURLWithPath:savePath] options:NSDataWritingAtomic error:&writeError];
                if (success) {
                    NSLog(@"Download completed!");
                } else {
                    NSLog(@"Error saving file: %@", writeError.localizedDescription);
                }
            }];
            
            // Start the task.
            [task resume];
            
            // Keep the main thread running so that the asynchronous request can be completed.
            [[NSRunLoop currentRunLoop] run];
        }
        return 0;
    }

Autres scénarios

Générer une URL pré-signée autorisant les requêtes HTTP GET pour une version spécifique d'un objet

L'exemple de code suivant montre comment générer une URL pré-signée autorisant les requêtes HTTP GET pour une version spécifique d'un objet :

# -*- 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint for 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 ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
object_name = 'exampledir/exampleobject.txt'

# Specify request headers.
headers = dict()
# Specify the version ID of the object.
headers["versionId"] = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****"

# Generate a presigned URL and set the validity period of the presigned URL to 600 seconds.
# By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the presigned URL cannot be directly used.
# 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, and the presigned URL can be directly used.
url = bucket.sign_url('PUT', object_name, 600, slash_safe=True, headers=headers)
print('Presigned URL:', url)

Utiliser une URL pré-signée contenant des en-têtes de requête spécifiques pour télécharger un objet

Si vous spécifiez des en-têtes de requête lors de la génération d'une URL pré-signée autorisant les requêtes HTTP GET, assurez-vous que ces en-têtes sont inclus dans la requête GET initiée via l'URL pré-signée. Cela permet d'éviter les échecs de requête et les erreurs de signature.

  1. Générez une URL pré-signée contenant des en-têtes de requête spécifiques et autorisant les requêtes HTTP GET.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Specify the endpoint for 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 ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
    region = "cn-hangzhou"
    
    # Specify the name of your bucket.
    bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
    
    # Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
    object_name = 'exampledir/exampleobject.txt'
    
    # Specify request headers.
    headers = dict()
    # Specify the Content-Type header.
    headers['Content-Type'] = 'text/plain; charset=utf8'
    
    # Specify HTTP query parameters.
    params = dict()
    # Configure single-connection bandwidth throttling. Unit: bit/s. In this example, the throttling threshold is set to 100 KB/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 VPC.
    # params['x-oss-ac-vpc-id'] = "vpc-t4nlw426y44rd3iq4xxxx"
    # Specify whether to allow request forwarding.
    # params['x-oss-ac-forward-allow'] = "true"
    
    # Generate a presigned URL that is used to download the object. In this example, the validity period of the URL is 600 seconds.
    # By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the presigned URL cannot be directly used.
    # 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, and the presigned URL can be directly used.
    url = bucket.sign_url('GET', object_name, 600, slash_safe=True, headers=headers, params=params)
    print('Presigned URL:', url)
  2. Utilisez l'URL pré-signée et spécifiez les en-têtes de requête dans la demande pour télécharger l'objet.

    curl -X GET "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241113T093321Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************&x-oss-signature=f1746f121783eed5dab2d665da95fbca08505263e27476a46f88dbe3702af8a9***************************************" \
    -H "Content-Type: text/plain" \
    -o "myfile.txt"
    import requests
    
    def download_file(signed_url, file_path, headers=None, metadata=None):
        """
        Use the presigned URL to download the object.
    
        :param signed_url: presigned URL
        :param file_path: full path of the object to download
        :param headers: request headers. This parameter is optional.
        :param metadata: user metadata. This parameter is optional.
        :return: None
        """
        if not headers:
            headers = {}
    
        try:
            response = requests.get(signed_url, headers=headers, stream=True)
            print(f"Download status code: {response.status_code}")
    
            if response.status_code == 200:
                with open(file_path, 'wb') as file:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:  # filter out keep-alive new chunks
                            file.write(chunk)
                print("The object is downloaded")
            else:
                print("Download failed")
                print(response.text)
        except Exception as e:
            print(f"An error occurred: {e}")
    
    if __name__ == "__main__":
        # Replace <signedUrl> with the generated presigned URL.
        signed_url = "<signedUrl>"
        file_path = "/Users/yourLocalPath>/Downloads/downloadedFile.txt" // Specify the local path in which the object is stored.  
    
        headers = {
            "Content-Type": "text/plain; charset=utf-8",
            # Other required headers
        }
    
        download_file(signed_url, file_path, headers=headers)

Générer une URL pré-signée à l'aide d'un nom de domaine personnalisé

L'exemple de code suivant montre comment générer une URL pré-signée en utilisant un nom de domaine personnalisé.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# 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.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the custom domain name. Example: static.example.com.
endpoint = 'http://static.example.com'

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region, is_cname=True)

# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
object_name = 'exampledir/exampleobject.txt'

# Generate a presigned URL that is used to download the object. In this example, the validity period of the URL is 600 seconds.
# By default, OSS identifies forward slashes (/) in the full path of an object as escape characters in the signing process. Therefore, the presigned URL cannot be directly used.
# 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, and the presigned URL can be directly used.
url = bucket.sign_url('GET', object_name, 600, slash_safe=True, params=params)
print('Presigned URL:', url)