Download an object by using a signed URL (Go SDK V1)

Updated at:

By default, objects in an Object Storage Service (OSS) bucket are private and can be accessed only by the object owner. You can use the Go software development kit (SDK) to generate a signed URL for a GET request. This URL allows other users to temporarily download the object. The URL can be used multiple times before it expires. After the URL expires, you must generate a new one.

Precautions

  • In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see Regions and endpoints.

  • The examples in this topic show how to read access credentials from environment variables. For more information about how to configure access credentials, see Configure access credentials (Go SDK V1).

  • This topic demonstrates creating an OSSClient instance with an OSS endpoint. For alternative configurations, such as using a custom domain or authenticating with credentials from Security Token Service (STS), see Client configuration.

  • You do not need permissions to generate a presigned URL. However, for a third party to download the object using the presigned URL, the user who generates the URL must have the oss:GetObject permission. For more information about how to grant permissions, see Grant custom permissions to a RAM user.

  • The examples in this topic use V4 signed URLs. The maximum validity period is 7 days. For more information, see Signature V4 (recommended).

Procedure

The following procedure describes how to download an object using a presigned URL:

image

Sample code

  1. The object owner generates a signed URL for a GET request.

    package main
    
    import (
    	"log"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    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 {
    		log.Printf("Error: %v\n", err)
    	}
    
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("cn-hangzhou"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		log.Printf("Error: %v\n", err)
    	}
    
    	// Specify the bucket name, for example, examplebucket.
    	bucketName := "examplebucket"
    	// Specify the object name, for example, exampleobject.txt. The object name cannot contain the bucket name.
    	objectName := "exampleobject.txt"
    	// Download the object to a local file and save it to the specified local path. If the specified local file exists, it is overwritten. If the file does not exist, it is created.
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		log.Printf("Error: %v\n", err)
    	}
    
    	// Generate a signed URL for downloading the object and set the validity period of the signed URL to 600 seconds.
    	signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 600)
    	if err != nil {
    		log.Printf("Error: %v\n", err)
    	}
    	log.Printf("Sign Url:%s\n", signedURL)
    }
    
  2. Other users download the object using the signed URL for the GET request.

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

Other scenarios

Generate a signed URL for a GET request to download a specific version of a file

The following sample code shows how to specify the object version when you generate a signed URL for a GET request. This allows other users to download a specific version of the object.

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

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 {
		log.Printf("Error: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("cn-hangzhou"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Printf("Error: %v", err)
	}

	// Specify the bucket name, for example, examplebucket.
	bucketName := "examplebucket"
	// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
	objectName := "exampledir/exampleobject.txt"
	// Download the object to a local file and save it to the specified local path. If the specified local file exists, it is overwritten. If the file does not exist, it is created.
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Printf("Error: %v", err)
	}

	// Specify the version ID of the file to download.
	options := []oss.Option{
		oss.VersionId("CAEQEhiBgIDmgPf8mxgiIDA1YjZlNDIxY2ZmMzQ1MmU5MTM1Y2M4Yzk4******"),
	}

	// Generate a signed URL for downloading the object and set the validity period of the signed URL to 600 seconds.
	signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 600, options...)
	if err != nil {
		log.Printf("Error: %v", err)
	}
	log.Printf("Sign Url:%s\n", signedURL)
}

Download a file using a signed URL with a specified request header

If you specify a request header when you generate a signed URL for a GET request, you must include the same request header in the GET request that uses the signed URL. Otherwise, the request fails due to a signature error.

  1. Generate a signed URL for a GET request that includes a request header.

    package main
    
    import (
    	"log"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    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 {
    		log.Printf("Error: %v", err)
    	}
    
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("cn-hangzhou"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		log.Printf("Error: %v", err)
    	}
    
    	// Specify the bucket name, for example, examplebucket.
    	bucketName := "examplebucket"
    	// Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
    	objectName := "exampledir/exampleobject.txt"
    	// Download the object to a local file and save it to the specified local path. If the specified local file exists, it is overwritten. If the file does not exist, it is created.
    	bucket, err := client.Bucket(bucketName)
    	if err != nil {
    		log.Printf("Error: %v", err)
    	}
    
    	// If you want to use a signed URL with optional parameters on the frontend, make sure that the ContentType set when generating the signed URL on the server is the same as the ContentType set on the frontend.
    	options := []oss.Option{
    		oss.ContentType("text/plain; charset=utf8"),
    	}
    
    	// Generate a signed URL for downloading the object and set the validity period of the signed URL to 600 seconds.
    	signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 600, options...)
    	if err != nil {
    		log.Printf("Error: %v", err)
    	}
    	log.Printf("Sign Url:%s\n", signedURL)
    }
    
  2. Download the object using the signed URL and specifying the request header.

    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=ed5a******************************************************" \
    -H "Content-Type: text/plain; charset=utf8" \
    -o "myfile.txt"
    package main
    
    import (
    	"io"
    	"log"
    	"net/http"
    	"os"
    )
    
    func main() {
    	// Specify the generated signed URL.
    	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=LTAI5************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a939feb8d79a389572719f7e2939939936d0**********"
    
    	// Use the generated signed URL to download the file using the HTTP GET method.
    	req, err := http.NewRequest(http.MethodGet, url, nil)
    	if err != nil {
    		log.Fatalf("Failed to create PUT request: %v", err)
    	}
    
    	//Set the Content-Type request header.
    	req.Header.Set("Content-Type", "text/plain")
    
    	// Send the request.
    	client := &http.Client{}
    	resp, err := client.Do(req)
    	if err != nil {
    		log.Fatalf("Failed to upload file: %v", err)
    	}
    	defer resp.Body.Close()
    
    	// Define the path of the local file to write to.
    	filePath := "downloadfile.txt"
    
    	// Create or open the local file.
    	file, err := os.Create(filePath)
    	if err != nil {
    		log.Fatalf("failed to create or open file: %v", err)
    	}
    	defer file.Close() // Make sure that the file is closed when the function ends.
    
    	// Use io.Copy to write the file content to the local file.
    	n, err := io.Copy(file, resp.Body)
    	if err != nil {
    		log.Fatalf("failed to read object %v", err)
    	}
    
    	// Close the response body.
    	err = resp.Body.Close()
    	if err != nil {
    		log.Printf("failed to close response body: %v", err)
    	}
    
    	log.Printf("wrote %d bytes to file: %s\n", n, filePath)
    }
    

References

  • For the complete sample code that shows how to download an object using a signed URL, see GitHub example.

  • For more information about the API operation that you can call to download an object using a signed URL, see SignURL.