OSS オブジェクトはデフォルトで非公開であり、ファイル所有者のみがアクセスできます。ただし、ファイル所有者は共有リンク (署名付き URL) を生成して、有効期間内に第三者が特定のファイルをオンラインでダウンロードまたはプレビューすることを許可できます。
対象読者:OSS オブジェクト (ファイル) を第三者と迅速に共有する必要があるユーザー、およびそれらの URL を受け取る第三者。これには、OSS を初めて使用するユーザーと、開発者や O&M エンジニアなどの技術ユーザーの両方が含まれます。
目的:すべてのレベルのユーザーが要件を満たし、期待どおりにアクセスできる署名付き URL を生成できるように支援し、第三者がそれらの URL を使用してリソースにアクセスできるように支援します。
仕組み
署名付き URL の生成は、秘密鍵の暗号化とパラメーターの連結に依存しています。プロセスは次のとおりです。
-
権限の検証:署名付き URL を生成する際、第三者が署名付き URL を通じてファイルを正常にダウンロード/プレビューできるようにするには、
oss:GetObject権限が必要です。 -
ローカルでの暗号化:AK/SK に基づいて、ファイルパス、有効期限などの情報を暗号化して計算し、署名 (
x-oss-signature) を取得します。 -
署名の追加:署名パラメーター (
x-oss-date、x-oss-expires、x-oss-credentialなど) をクエリ文字列としてファイル URL に追加します。 -
リンクの形成:完全な署名付き URL を構成します。
署名付き URL のフォーマット
https://BucketName.Endpoint/Object?signature parameters完全な例
https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-process=image%2Fresize%2Cp_10&x-oss-date=20241115T095058Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************%2F20241115%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=6e7a*********************************
詳細な生成プロセスについては、「署名バージョン 4 (推奨)」をご参照ください。
ファイルダウンロードリンクの取得
OSS のデフォルトエンドポイントを使用して、有効期限付きのファイルダウンロードリンク (署名付き URL) を生成します。
OSS コンソールの使用
OSS 管理コンソールにログインし、対象バケットの [ファイル] リストに移動し、対象ファイルをクリックしてから、右側の詳細パネルで [ファイル URL をコピー] をクリックすると、デフォルトの有効期間が 300 秒 (5 分) の一時的なダウンロードリンクを取得できます。
Alibaba Cloud SDK の使用
以下は、一般的な言語でファイルダウンロードリンク (署名付き URL) を生成するためのコード例です。
Java
詳細については、「Java で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import java.net.URL;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Throwable {
// この例では、中国 (杭州) リージョンのパブリックエンドポイントを使用します。実際のエンドポイントを指定してください。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケット名を入力します。例:examplebucket。
String bucketName = "examplebucket";
// オブジェクトの完全なパスを入力します。例:exampleobject.txt。完全なパスにバケット名を含めることはできません。
String objectName = "exampleobject.txt";
// バケットが配置されているリージョンを入力します。たとえば、バケットが中国 (杭州) リージョンにある場合、リージョンを cn-hangzhou に設定します。
String region = "cn-hangzhou";
// OSSClient インスタンスを作成します。
// OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 署名付き URL の有効期限をミリ秒単位で設定します。この例では、有効期限を 1 時間に設定します。
Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
// GET リクエスト用の署名付き URL を生成します。この例では、追加のリクエストヘッダーは含まれていません。他のユーザーはブラウザを介して直接コンテンツにアクセスできます。
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
System.out.println(url);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}Python
詳細については、「Python で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
import argparse
import alibabacloud_oss_v2 as oss
# コマンドライン引数パーサーを作成し、スクリプトの目的を記述します。
parser = argparse.ArgumentParser(description="presign get object sample")
# --region パラメーターを指定して、バケットが配置されているリージョンを示します。このパラメーターは必須です。
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# --bucket パラメーターを指定して、オブジェクトが格納されているバケットの名前を示します。このパラメーターは必須です。
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# --endpoint パラメーターを指定して、バケットが配置されているリージョンのエンドポイントを示します。このパラメーターはオプションです。
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# --key パラメーターを指定して、オブジェクトの名前を示します。このパラメーターは必須です。
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# コマンドライン引数を解析して、指定された値を取得します。
args = parser.parse_args()
# 環境変数から、OSS へのアクセスに必要な認証情報をロードします。
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# デフォルト設定を使用して cfg オブジェクトを作成し、認証情報プロバイダーを指定します。
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# cfg オブジェクトのリージョン属性を、コマンドラインで指定されたリージョンに設定します。
cfg.region = args.region
# カスタムエンドポイントが指定されている場合、cfg オブジェクトのエンドポイント属性を指定されたエンドポイントで更新します。
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# 上記の設定を使用して OSSClient インスタンスを初期化します。
client = oss.Client(cfg)
# 署名付き URL を生成するリクエストを開始します。
pre_result = client.presign(
oss.GetObjectRequest(
bucket=args.bucket, # バケット名を指定します。
key=args.key, # オブジェクトキーを指定します。
)
)
# HTTP メソッド、有効期限、署名付き URL を表示します。
print(f'method: {pre_result.method},'
f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
f' url: {pre_result.url}'
)
# 署名付きヘッダーを表示します。
for key, value in pre_result.signed_headers.items():
print(f'signed headers key: {key}, signed headers value: {value}')
# スクリプトが直接実行されたときに、main 関数を呼び出して処理ロジックを開始します。
if __name__ == "__main__":
main() # スクリプトのエントリポイントを指定します。制御フローはここから始まります。Go
詳細については、「Go で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// グローバル変数を定義します。
var (
region string // バケットが配置されているリージョン。
bucketName string // バケットの名前。
objectName string // オブジェクトの名前。
)
// init 関数は、コマンドライン引数を初期化するために使用されます。
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// コマンドライン引数を解析します。
flag.Parse()
// バケット名が空かどうかを確認します。
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// リージョンが空かどうかを確認します。
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// オブジェクト名が空かどうかを確認します。
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// デフォルト設定をロードし、認証情報プロバイダーとリージョンを指定します。
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// OSS クライアントを作成します。
client := oss.NewClient(cfg)
// GetObject リクエストの署名付き URL を生成します。
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
},
oss.PresignExpires(10*time.Minute),
)
if err != nil {
log.Fatalf("failed to get object presign %v", err)
}
log.Printf("request method:%v\n", result.Method)
log.Printf("request expiration:%v\n", result.Expiration)
log.Printf("request url:%v\n", result.URL)
if len(result.SignedHeaders) > 0 {
// 返された結果に署名付きヘッダーが含まれている場合、署名付き URL を使用して GET リクエストを送信する際に、対応するリクエストヘッダーを含める必要があります。そうしないと、リクエストが失敗したり、署名エラーが発生したりする可能性があります。
log.Printf("signed headers:\n")
for k, v := range result.SignedHeaders {
log.Printf("%v: %v\n", k, v)
}
}
}
Node.js
詳細については、「Node.js で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
const OSS = require("ali-oss");
// 署名付き URL を生成する関数を定義します。
async function generateSignatureUrl(fileName) {
// 署名付き URL を取得します。
const client = await new OSS({
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: 'examplebucket',
// yourregion をバケットが配置されているリージョンに置き換えます。たとえば、バケットが中国 (杭州) リージョンにある場合、リージョンを oss-cn-hangzhou に設定します。
region: 'oss-cn-hangzhou',
// secure を true に設定して HTTPS を使用します。これにより、ブラウザが生成されたダウンロードリンクをブロックするのを防ぎます。
secure: true,
authorizationV4: true
});
return await client.signatureUrlV4('GET', 3600, {
headers: {} // 実際のリクエストヘッダーに基づいてリクエストヘッダーを設定します。
}, fileName);
}
// 関数を呼び出し、ファイル名を渡します。
generateSignatureUrl('yourFileName').then(url => {
console.log('Generated Signature URL:', url);
}).catch(err => {
console.error('Error generating signature URL:', err);
});PHP
詳細については、「PHP で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
<?php
// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description for command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint to access OSS. (Optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. (Required)
"key" => ['help' => 'The name of the object', 'required' => True], // The object name. (Required)
"expire" => ['help' => 'The expiration time in seconds (default: 900)', 'required' => False], // The expiration time in seconds. (Optional, default: 900)
];
// Convert the argument descriptions to the long options format required by getopt.
// A colon ":" after each argument indicates that it requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line arguments.
$options = getopt("", $longopts);
// Check if all required arguments are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Get the help information for the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"]; // The object name.
$expire = isset($options["expire"]) ? (int)$options["expire"] : 900; // The expiration time. Default: 900 seconds.
// Load the credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set it.
}
try {
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a GetObjectRequest object to download the object.
$request = new Oss\Models\GetObjectRequest(bucket:$bucket, key:$key);
// Call the presign method to generate a signed URL and set the expiration time.
$result = $client->presign($request, [
'expires' => new \DateInterval("PT{$expire}S") // PT stands for Period Time, and S stands for seconds.
]);
// Output the signed URL.
echo "Signed URL: " . $result->url . PHP_EOL;
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . PHP_EOL;
exit(1);
}.NET
詳細については、「.NET で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
using Aliyun.OSS;
using Aliyun.OSS.Common;
// バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 環境変数から認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// バケットの名前を指定します。例:examplebucket。
var bucketName = "examplebucket";
// オブジェクトの完全なパスを指定します。完全なパスにバケット名を含めることはできません。例:exampledir/exampleobject.txt。
var objectName = "exampledir/exampleobject.txt";
// バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合、リージョンを cn-hangzhou に設定します。
const string region = "cn-hangzhou";
// ClientConfiguration インスタンスを作成し、要件に基づいてデフォルトのパラメーターを変更します。
var conf = new ClientConfiguration();
// V4 署名を指定します。
conf.SignatureVersion = SignatureVersion.V4;
// OSSClient インスタンスを作成します。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
var metadata = client.GetObjectMetadata(bucketName, objectName);
var etag = metadata.ETag;
// 署名付き URL を生成します。
var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
{
// 署名付き URL の有効期間を設定します。デフォルト値:3600。単位:秒。
Expiration = DateTime.UtcNow.AddHours(1),
};
var uri = client.GeneratePresignedUri(req);
// 生成された署名付き URL を出力します
Console.WriteLine("Generated Signed URL: " + uri);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}Android
SDK の詳細については、「Android で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
// バケット名を指定します。例:examplebucket。
String bucketName = "examplebucket";
// ソースオブジェクトの完全なパスを、バケット名なしで指定します。例:exampleobject.txt。
String objectKey = "exampleobject.txt";
String url = null;
try {
// ファイルをダウンロードするための署名付き URL を生成します。
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
// 署名付き URL の有効期限を 30 分に設定します。
request.setExpiration(30*60);
request.setMethod(HttpMethod.GET);
url = oss.presignConstrainedObjectURL(request);
Log.d("url", url);
} catch (ClientException e) {
e.printStackTrace();
}iOS
SDK の詳細については、「iOS で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
// バケットの名前を指定します。
NSString *bucketName = @"examplebucket";
// オブジェクトの名前を指定します。
NSString *objectKey = @"exampleobject.txt";
__block NSString *urlString;
// オブジェクトをダウンロードするための有効期間付きの署名付き URL を生成します。この例では、URL の有効期間は 30 分です。
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;
}];C++
SDK の詳細については、「C++ で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* OSS へのアクセスに使用するアカウントに関する情報を初期化します。*/
/* バケットが配置されているリージョンのエンドポイントを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。*/
std::string Endpoint = "yourEndpoint";
/* バケットが配置されているリージョンを指定します。たとえば、バケットが中国 (杭州) リージョンにある場合、リージョンを cn-hangzhou に設定します。 * /
std::string Region = "yourRegion";
/* バケットの名前を指定します。例:examplebucket。*/
std::string BucketName = "examplebucket";
/* オブジェクトの完全なパスを指定します。完全なパスにバケット名を含めないでください。例:exampledir/exampleobject.txt。*/
std::string GetobjectUrlName = "exampledir/exampleobject.txt";
/* ネットワークリソースなどのリソースを初期化します。*/
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 環境変数からアクセス認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。*/
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* 事前署名付き URL の有効期間を指定します。最大有効期間は 32,400 です。単位:秒。*/
std::time_t t = std::time(nullptr) + 1200;
/* 事前署名付き URL を生成します。*/
auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
if (genOutcome.isSuccess()) {
std::cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << std::endl;
}
else {
/* 例外を処理します。*/
std::cout << "GeneratePresignedUrl fail" <<
",code:" << genOutcome.error().Code() <<
",message:" << genOutcome.error().Message() <<
",requestId:" << genOutcome.error().RequestId() << std::endl;
return -1;
}
/* ネットワークリソースなどのリソースを解放します。*/
ShutdownSdk();
return 0;
}Ruby
SDK の詳細については、「Ruby で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# 中国 (杭州) エンドポイントを例として使用します。実際のリージョンに基づいてエンドポイントを指定してください。
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# 環境変数からアクセス認証情報を取得します。このサンプルコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# バケット名を指定します。例:examplebucket。
bucket = client.get_bucket('examplebucket')
# 署名付き URL を生成し、その有効期間を 1 時間 (3600 秒) に設定します。
puts bucket.object_url('my-object', true, 3600)C
SDK の詳細については、「C で署名付き URL を使用してファイルをダウンロードする」をご参照ください。
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the full path of the local file. */
const char *local_filename = "yourLocalFilename";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize the aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool (pool) for memory management, which is equivalent to apr_pool_t. Its implementation code is in the APR library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client option oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object;
aos_string_t file;
aos_http_request_t *req;
apr_time_t now;
char *url_str;
aos_string_t url;
int64_t expire_time;
int one_hour = 3600;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
aos_str_set(&file, local_filename);
expire_time = now / 1000000 + one_hour;
req = aos_http_request_create(pool);
req->method = HTTP_GET;
now = apr_time_now();
/* Unit: microseconds. */
expire_time = now / 1000000 + one_hour;
/* Generate a presigned URL. */
url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
aos_str_set(&url, url_str);
printf("Temporary download URL: %s\n", url_str);
/* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}生成された署名付き URL の例は次のとおりです。
https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-process=image%2Fresize%2Cp_10&x-oss-date=20241115T095058Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************%2F20241115%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=6e7a*********************************************
コマンドラインツール ossutil の使用
examplebucket バケット内の example.txt オブジェクトに対して、デフォルトの有効期間が 15 分のファイルダウンロードリンク (署名付き URL) を次のコマンドで生成します。
ossutil presign oss://examplebucket/example.txt
ossutil を使用して署名付き URL を生成するその他の例については、「presign (署名付き URL の生成)」をご参照ください。
グラフィカル管理ツール ossbrowser の使用
ossbrowser は、コンソールでサポートされているものと同様のオブジェクトレベルの操作をサポートしています。ossbrowser のインターフェイスに従って、署名付き URL を取得する操作を完了してください。ossbrowser の使用方法については、「常用操作」をご参照ください。
ファイルのオンラインプレビューリンクの取得
オンラインプレビューをサポートするリンク (署名付き URL) を生成するには、まずカスタムドメイン名をアタッチする必要があります。カスタムドメイン名をアタッチした後、それを使用して署名付き URL を生成します。
OSS コンソールの使用
-
OSS コンソールにログインします。
-
左側のナビゲーションウィンドウで、[バケット] をクリックします。バケットページで、バケットの名前をクリックします。
-
左側のナビゲーションツリーで、 を選択します。
-
オブジェクトページで、オブジェクトの名前をクリックします。
-
[詳細の表示] パネルで、[カスタムドメイン名] フィールドでバケットにマッピングされているカスタムドメイン名を選択し、他のパラメーターはデフォルト設定のままにして、[オブジェクト URL をコピー] をクリックします。

ossbrowser の使用
ossbrowser を使用して、OSS コンソールで実行できるのと同じオブジェクトレベルの操作を実行できます。ossbrowser の画面上の指示に従って、署名付き URL を取得できます。ossbrowser のダウンロード方法については、「ossbrowser 1.0」をご参照ください。
-
カスタムドメイン名を使用して ossbrowser にログインします。
-
オブジェクトの URL を取得します。
OSS SDK の使用
カスタムドメイン名を使用して OssClient インスタンスを作成し、署名付き URL を生成できます。
Java
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 {
// yourCustomEndpoint をカスタムドメイン名に設定します。例:http://static.example.com。
String endpoint = "yourCustomEndpoint";
// バケットのリージョン情報を入力します。例:cn-hangzhou。
String region = "cn-hangzhou";
// バケット名を入力します。例:examplebucket。
String bucketName = "examplebucket";
// オブジェクトの完全なパスを入力します。例:exampleobject.txt。完全なパスにバケット名を含めることはできません。
String objectName = "exampleobject.txt";
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、環境変数を設定してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// OSSClient インスタンスを作成します。
// OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// 注:CNAME オプションを有効にするには、これを true に設定します。
clientBuilderConfiguration.setSupportCname(true);
// V4 署名アルゴリズムの使用を明示的に宣言します。
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 生成された署名付き URL の有効期限をミリ秒単位で設定します。この例では、有効期限を 1 時間に設定します。
Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
// 署名付き URL を生成します。
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
// 有効期限を設定します。
request.setExpiration(expiration);
// HTTP GET リクエスト用の署名付き URL を生成します。
URL signedUrl = ossClient.generatePresignedUrl(request);
// 署名付き 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());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
PHP
<?php
// 依存関係ライブラリが正しくロードされるように、オートローダーファイルをインポートします。
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// コマンドライン引数の説明を定義します。
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // バケットが配置されているリージョン。(必須)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // OSS にアクセスするためのエンドポイント。(オプション)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // バケット名。(必須)
"key" => ['help' => 'The name of the object', 'required' => True], // オブジェクト名。(必須)
];
// 引数の説明を getopt で必要なロングオプション形式に変換します。
// 各引数の後のコロン「:」は、値が必要であることを示します。
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// コマンドライン引数を解析します。
$options = getopt("", $longopts);
// 必須の引数がすべて提供されているか確認します。
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // 引数のヘルプ情報を取得します。
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // 必須の引数が欠落している場合、プログラムを終了します。
}
}
// 解析された引数から値を抽出します。
$region = $options["region"]; // バケットが配置されているリージョン。
$bucket = $options["bucket"]; // バケット名。
$key = $options["key"]; // オブジェクト名。
// 環境変数から認証情報をロードします。
// EnvironmentVariableCredentialsProvider を使用して、環境変数からアクセスキー ID とアクセスキーシークレットを読み取ります。
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// SDK のデフォルト設定を使用します。
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // 認証情報プロバイダーを設定します。
$cfg->setRegion($region); // バケットが配置されているリージョンを設定します。
$cfg->setEndpoint(endpoint: "http://static.example.com"); // これをカスタムエンドポイントに設定します。
$cfg->setUseCname(true); // CNAME を使用するように設定します。
// OSS クライアントインスタンスを作成します。
$client = new Oss\Client($cfg);
// オブジェクトをダウンロードするための GetObjectRequest オブジェクトを作成します。
$request = new Oss\Models\GetObjectRequest(bucket:$bucket, key:$key);
// presign メソッドを呼び出して、署名付き URL を生成します。
$result = $client->presign($request);
// presign の結果を出力します。
// 署名付き URL を出力します。ユーザーはこれを直接使用してオブジェクトをダウンロードできます。
print(
'get object presign result:' . var_export($result, true) . PHP_EOL . // presign 結果の詳細情報。
'get object url:' . $result->url . PHP_EOL // オブジェクトを直接ダウンロードするための署名付き URL。
);
Node.js
const OSS = require("ali-oss");
// 署名付き URL を生成する関数を定義します。
async function generateSignatureUrl(fileName) {
// 署名付き URL を取得します。
const client = await new OSS({
// カスタムドメイン名をエンドポイントとして使用します。
endpoint: 'http://static.example.com',
// 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: 'examplebucket',
// yourregion をバケットが配置されているリージョンに置き換えます。たとえば、バケットが中国 (杭州) リージョンにある場合、リージョンを oss-cn-hangzhou に設定します。
region: 'oss-cn-hangzhou',
authorizationV4: true,
cname: true
});
return await client.signatureUrlV4('GET', 3600, {
headers: {} // 実際のリクエストヘッダーに基づいてリクエストヘッダーを設定します。
}, fileName);
}
// 関数を呼び出し、ファイル名を渡します。
generateSignatureUrl('yourFileName').then(url => {
console.log('Generated Signature URL:', url);
}).catch(err => {
console.error('Error generating signature URL:', err);
});
Python
import argparse
import alibabacloud_oss_v2 as oss
# コマンドライン引数パーサーを作成し、スクリプトの目的を記述します。
parser = argparse.ArgumentParser(description="presign get object sample")
# --region パラメーターを指定して、バケットが配置されているリージョンを示します。このパラメーターは必須です。
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# --bucket パラメーターを指定して、オブジェクトが格納されているバケットの名前を示します。このパラメーターは必須です。
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# --endpoint パラメーターを指定して、バケットが配置されているリージョンのエンドポイントを示します。このパラメーターはオプションです。
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# --key パラメーターを指定して、オブジェクトの名前を示します。このパラメーターは必須です。
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# コマンドライン引数を解析して、指定された値を取得します。
args = parser.parse_args()
# 環境変数から、OSS へのアクセスに必要な認証情報をロードします。
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# デフォルト設定を使用して cfg オブジェクトを作成し、認証情報プロバイダーを指定します。
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# ユーザーが指定したコマンドラインパラメーターに基づいて、設定オブジェクトのリージョン属性を指定します。
cfg.region = args.region
# カスタムエンドポイントを指定します。例:http://static.example.com
cfg.endpoint = "http://static.example.com"
# CNAME レコード解決を有効にします。
cfg.use_cname = True
# 上記の設定を使用して OSSClient インスタンスを初期化します。
client = oss.Client(cfg)
# 署名付き URL を生成するリクエストを開始します。
pre_result = client.presign(
oss.GetObjectRequest(
bucket=args.bucket, # バケット名を指定します。
key=args.key, # オブジェクトキーを指定します。
)
)
# HTTP メソッド、有効期限、署名付き URL を表示します。
print(f'method: {pre_result.method},'
f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
f' url: {pre_result.url}'
)
# 署名付きヘッダーを表示します。
for key, value in pre_result.signed_headers.items():
print(f'signed headers key: {key}, signed headers value: {value}')
# スクリプトが直接実行されたときに、main 関数を呼び出して処理ロジックを開始します。
if __name__ == "__main__":
main() # スクリプトのエントリポイントを指定します。制御フローはここから始まります。
Go
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// グローバル変数を定義します。
var (
region string // バケットが配置されているリージョン。
bucketName string // バケットの名前。
objectName string // オブジェクトの名前。
)
// init 関数は、コマンドライン引数を初期化するために使用されます。
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// コマンドライン引数を解析します。
flag.Parse()
// バケット名が空かどうかを確認します。
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// リージョンが空かどうかを確認します。
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// オブジェクト名が空かどうかを確認します。
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// デフォルト設定をロードし、認証情報プロバイダーとリージョンを指定します。
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region).
WithEndpoint("http://static.example.com").
WithUseCName(true)
// OSS クライアントを作成します。
client := oss.NewClient(cfg)
// GetObject リクエストの署名付き URL を生成します。
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
//RequestPayer: oss.Ptr("requester"), // リクエスタの ID を指定します。
},
oss.PresignExpires(10*time.Minute),
)
if err != nil {
log.Fatalf("failed to get object presign %v", err)
}
log.Printf("request method:%v\n", result.Method)
log.Printf("request expiration:%v\n", result.Expiration)
log.Printf("request url:%v\n", result.URL)
if len(result.SignedHeaders) > 0 {
// HTTP GET リクエストを許可する署名付き URL を生成する際にリクエストヘッダーを指定した場合、署名付き URL を使用して開始される GET リクエストにリクエストヘッダーが含まれていることを確認してください。これにより、リクエストの失敗や署名エラーを防ぐことができます。
log.Printf("signed headers:\n")
for k, v := range result.SignedHeaders {
log.Printf("%v: %v\n", k, v)
}
}
}
ossutil の使用
presign (署名付き URL の生成) コマンドを実行して、カスタムドメイン名を使用してオブジェクトの署名付き URL を生成します。
ossutil presign oss://examplebucket/exampleobject.txt --endpoint "http://static.example.com” --addressing-style "cname"
ossutil コマンドが毎回手動で指定する代わりに、自動的にカスタムドメイン名を使用できるようにするには、カスタムドメイン名を設定ファイルに追加します。
リンクがまだプレビューできない場合は、次の設定を確認してください。
-
Content-Typeは適切に設定されていますか?ファイルの
Content-Typeが実際のタイプと一致しない場合、ブラウザはコンテンツを正しく識別してレンダリングできず、ファイルが添付ファイルとしてダウンロードされる可能性があります。Content-Type (MIME) の設定方法 を確認して、ファイル名拡張子がContent-Typeと一致するかどうかを確認できます。一致しない場合は、「オブジェクトのメタデータの管理」を参照して、ファイルのContent-Typeを変更する方法を確認してください。 -
Content-Dispositionはinlineに設定されていますか?ファイルの
Content-Dispositionがattachmentに設定されている場合、ブラウザはファイルを強制的にダウンロードします。「オブジェクトのメタデータの管理」を参照して、プレビューをサポートするためにinlineに変更する方法を確認してください。 -
CDN キャッシュはリフレッシュされましたか?
CDN 加速を使用していない場合は、この項目を無視できます。
CDN を使用して OSS リソースにアクセスする場合、ファイルメタデータを変更した後に CDN キャッシュをリフレッシュする必要があります。そうしないと、古い設定がまだ読み取られ、プレビューが有効にならない可能性があります。
ファイルの強制ダウンロードリンクの取得
現在のリンク (署名付き URL) がブラウザで直接プレビュー用に開かれるが、代わりにダウンロードさせたい場合は、次の方法を使用できます。方法 1 は方法 2 よりも優先度が高いです。
方法 1:一回限りの強制ダウンロード
これは現在生成されているリンクにのみ適用されます。URL を生成する際に response-content-disposition パラメーターを attachment に設定することで実装します。
Java
GeneratePresignedUrlRequest クラスをインポートします。
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
GeneratePresignedUrlRequest メソッドを使用し、response-content-disposition レスポンスヘッダーを attachment に設定します。
// GET リクエスト用の署名付き URL を構築
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
bucketName, objectName, HttpMethod.GET);
// 強制ダウンロードを設定
request.getResponseHeaders().setContentDisposition("attachment");
Python
GetObjectRequest に response_content_disposition パラメーターを追加し、その値を attachment に設定します。
# 署名付き GET リクエストを生成
pre_result = client.presign(
oss.GetObjectRequest(
bucket=args.bucket, # バケット名を指定
key=args.key, # オブジェクトキーを指定
response_content_disposition="attachment",# 強制ダウンロードに設定
)
)
Go
GetObjectRequest に ResponseContentDisposition パラメーターを追加し、その値を attachment に設定します。
// 強制ダウンロード動作を持つ署名付き GET リクエストを生成
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
ResponseContentDisposition: oss.Ptr("attachment"), // 強制ダウンロードに設定
})
方法 2:共通の強制ダウンロード設定 (メタデータ経由)
一度設定すると、ファイルへのすべてのアクセスが強制的にダウンロードされるようになります。これは、ファイルメタデータの Content-Disposition フィールドを変更することで実装されます。
OSS コンソールの使用
OSS 管理コンソールで、対象のファイルを見つけ、ファイル詳細パネルで [ファイルメタデータの設定] をクリックし、Content-Disposition を attachment に設定し、[OK] をクリックして保存します。
コンソール操作に加えて、「ファイルメタデータの管理」を参照して、SDK またはコマンドラインインターフェイス ossutil を使用してこのフィールドを設定することもできます。
ダウンロード時に表示されるファイル名をカスタマイズしたい場合は、「ダウンロード時のファイル名のカスタマイズ」をご参照ください。
特定バージョンのファイルリンクの取得
バージョン管理が有効になっているバケットに適用される、特定バージョンのファイルのリンク (署名付き URL) を生成します。
OSS コンソールの使用
-
OSS 管理コンソールにログインし、対象バケットの [ファイル] タブに移動し、ページ右上隅の [履歴バージョン] を [表示] に切り替えます。

-
対象のファイルを見つけ、必要な履歴バージョンのファイル名をクリックし、詳細ページでこのバージョンファイルの URL を [コピー] します。

Alibaba Cloud SDK の使用
Java
次のキーコードを追加します。
// 1. バージョン ID 変数を定義します
String versionId = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****";
// 2. クエリパラメーターマップを作成します
Map<String, String> queryParam = new HashMap<String, String>();
queryParam.put("versionId", versionId);
// 3. リクエストにバージョン ID パラメーターを追加します
request.setQueryParameter(queryParam);
Python
GetObjectRequest に version_id パラメーターを追加します。
pre_result = client.presign(
oss.GetObjectRequest(
bucket=bucket_name,
key=object_name,
version_id='CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****' # VersionId パラメーターを設定
)
)
Go
GetObjectRequest に VersionId フィールドを追加します。
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
VersionId: oss.Ptr("CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE7****"), // VersionId を設定
}, oss.PresignExpires(10*time.Minute))
Node.js
signatureUrlV4 に queries パラメーターを追加します。
const signedUrl = await client.signatureUrlV4('GET', 3600, {
queries: {
"versionId": 'CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE7****' // versionId パラメーターを追加
}
}, objectName);
PHP
GetObjectRequest に、versionId パラメーターを追加します。
// 特定のバージョンパラメーターを追加
$versionId = "yourVersionId"; // 実際のバージョン番号に置き換えます
$request = new Oss\Models\GetObjectRequest(bucket:$bucket, key:$key, versionId:$versionId);
ossutil の使用
examplebucket バケット内のバージョン ID 123 の example.txt オブジェクトの署名付き URL を生成します。
ossutil presign oss://examplebucket/example.txt --version-id 123
ファイルリンクの一括生成
コマンドラインインターフェイス ossutil を使用することをお勧めします。これにより、フォルダ全体のファイルリンクを一括で生成できます。
コマンドラインインターフェイス ossutil の使用
-
examplebucke バケットのフォルダディレクトリ内のすべてのファイルに対して、デフォルトの有効期間が 15 分の署名付き URL を生成します。
ossutil presign oss://examplebucket/folder/ -r -
examplebucket バケットのフォルダディレクトリ内の .txt 拡張子を持つファイルに対して、デフォルトの有効期間が 15 分の署名付き URL を生成します。
ossutil presign oss://examplebucket/folder/ -r --include "*.txt" -
examplebucket バケット内のすべてのファイルに対して、デフォルトの有効期間が 15 分の署名付き URL を生成します。
ossutil presign oss://examplebucket/ -r
ossutil を使用した署名付き URL の生成に関する詳細については、「presign (署名付き URL の生成)」をご参照ください。
OSS コンソールの使用
現在のディレクトリ内のファイルの署名付き URL のみをエクスポートできます。サブディレクトリ内のファイルの署名付き URL はエクスポートできません。
-
オブジェクトファイルを選択し、下の [URL リストのエクスポート] をクリックします。

-
表示される設定パネルでは、デフォルトのパラメーターがほとんどのシナリオに適しており、変更せずに使用できます。
-
OK をクリックして、生成された URL リストファイルをダウンロードして保存します。
Alibaba Cloud SDK の使用
GetBucket (ListObjects) 操作を使用してすべてのオブジェクト名を取得し、各オブジェクトの署名付き URL を生成します。
ダウンロードファイル名のカスタマイズ
強制ダウンロードに基づいて、ユーザーがファイルを保存する際に表示されるファイル名をさらに指定できます。方法 1 は方法 2 よりも優先度が高いです。
方法 1:単一リクエストのダウンロードファイル名を設定する
単一の署名付き URL のダウンロードファイル名を指定します。response-content-disposition パラメーターを attachment に設定し、filename パラメーターを含めるだけで済みます。
Java
response-content-disposition パラメーターを設定します。
// クライアントがダウンロードする際に表示されるファイル名を設定します。例として "test.txt" を使用します
String filename = "test.txt";
request.getResponseHeaders().setContentDisposition("attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
Python
response_content_disposition パラメーターを使用して、ダウンロードファイル名を test.txt にカスタマイズします。
# 署名付き GET リクエストを生成
pre_result = client.presign(
oss.GetObjectRequest(
bucket=args.bucket, # バケット名を指定
key=args.key, # オブジェクトキーを指定
response_content_disposition="attachment;filename=test.txt",# クライアントがダウンロードする際に表示されるファイル名を設定します。この場合は "test.txt"
)
)
Go
ResponseContentDisposition パラメーターを使用して、ダウンロードファイル名を test.txt にカスタマイズします。
// 強制ダウンロード動作を持つ署名付き GET リクエストを生成
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
ResponseContentDisposition: oss.Ptr("attachment;filename=test.txt"),//クライアントがダウンロードする際に表示されるファイル名を設定します。この場合は "test.txt"
})
方法 2:共通の設定 (メタデータ経由)
メタデータを変更して、すべてのアクセスに対して統一されたデフォルトのダウンロード名を設定します。これは、ファイルメタデータの Content-Disposition フィールドを attachment; filename="yourFileName" に変更することで実装されます。ここで、yourFileName はカスタムファイル名です (例:example.jpg)。
リンクの有効期間の設定
リンク (署名付き URL) の有効期間は生成時に設定され、後で変更することはできません。リンクは有効期間中に複数回アクセスでき、期限が切れると無効になります。
生成方法によってサポートされる最大有効期間は異なります。制限を超えると、生成の失敗やアクセス例外が発生します。
OSS コンソールの使用
OSS 管理コンソールにログインし、対象バケットの [ファイル] リストに移動し、対象ファイルをクリックして、右側の詳細パネルの [有効期限] でリンクの有効期間を設定します。
Alibaba Cloud SDK の使用
第三者が署名付き URL を通じてファイルを正常にダウンロードできるようにするには、oss:GetObject 権限が必要です。具体的な権限付与操作については、「RAM ユーザーにカスタム権限を付与する」をご参照ください。生成後、ファイルにアクセスする必要がある第三者にリンクを送信できます。
コード内の有効期限を変更することで、署名付き URL の有効期限を設定できます。
Java
SDK の詳細については、「Java で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import java.net.URL;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Throwable {
// This example uses the public endpoint of the China (Hangzhou) region. Specify the actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Enter the bucket name. For example, examplebucket.
String bucketName = "examplebucket";
// Enter the full path of the object. For example, exampleobject.txt. The full path cannot contain the bucket name.
String objectName = "exampleobject.txt";
// Enter the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Set the expiration time of the presigned URL in milliseconds. This example sets the expiration time to one hour.
Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
// Generate a presigned URL for a GET request. This example does not include additional request headers. Other users can directly access the content through a browser.
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
System.out.println(url);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}Python
SDK の詳細については、「Python で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line parameter parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="presign get object sample")
# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket in which the object is stored. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter to indicate the name of the object. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# Parse the command-line parameters to obtain the specified values.
args = parser.parse_args()
# From the environment variables, load the authentication information required to access OSS.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configuration to create a cfg object and specify the credential provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region attribute of the cfg object to the region provided in the command line.
cfg.region = args.region
# If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Use the preceding settings to initialize the OSSClient instance.
client = oss.Client(cfg)
# Initiate a request to generate a presigned URL.
pre_result = client.presign(
oss.GetObjectRequest(
bucket=args.bucket, # Specify the bucket name.
key=args.key, # Specify the object key.
)
)
# Display the HTTP method, expiration time, and presigned URL.
print(f'method: {pre_result.method},'
f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
f' url: {pre_result.url}'
)
# Display the signed headers.
for key, value in pre_result.signed_headers.items():
print(f'signed headers key: {key}, signed headers value: {value}')
# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
main() # Specify the entry point of the script. The control flow starts here.Go
SDK の詳細については、「Go で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Generate a presigned URL for the GetObject request.
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
},
oss.PresignExpires(10*time.Minute),
)
if err != nil {
log.Fatalf("failed to get object presign %v", err)
}
log.Printf("request method:%v\n", result.Method)
log.Printf("request expiration:%v\n", result.Expiration)
log.Printf("request url:%v\n", result.URL)
if len(result.SignedHeaders) > 0 {
// If the returned result contains signed headers, you must include the corresponding request headers when you send a GET request using the presigned URL. Otherwise, the request may fail or a signature error may occur.
log.Printf("signed headers:\n")
for k, v := range result.SignedHeaders {
log.Printf("%v: %v\n", k, v)
}
}
}
Node.js
SDK の詳細については、「Node.js で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
const OSS = require("ali-oss");
// Define a function to generate a presigned URL.
async function generateSignatureUrl(fileName) {
// Obtain the presigned URL.
const client = await new OSS({
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: 'examplebucket',
// Replace yourregion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Set secure to true to use HTTPS. This prevents the browser from blocking the generated download link.
secure: true,
authorizationV4: true
});
return await client.signatureUrlV4('GET', 3600, {
headers: {} // Set the request headers based on the actual request headers.
}, fileName);
}
// Call the function and pass the file name.
generateSignatureUrl('yourFileName').then(url => {
console.log('Generated Signature URL:', url);
}).catch(err => {
console.error('Error generating signature URL:', err);
});PHP
SDK の詳細については、「PHP で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
<?php
// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define the description for command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. (Required)
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint to access OSS. (Optional)
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. (Required)
"key" => ['help' => 'The name of the object', 'required' => True], // The object name. (Required)
"expire" => ['help' => 'The expiration time in seconds (default: 900)', 'required' => False], // The expiration time in seconds. (Optional, default: 900)
];
// Convert the argument descriptions to the long options format required by getopt.
// A colon ":" after each argument indicates that it requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line arguments.
$options = getopt("", $longopts);
// Check if all required arguments are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Get the help information for the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is missing, exit the program.
}
}
// Extract values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"]; // The object name.
$expire = isset($options["expire"]) ? (int)$options["expire"] : 900; // The expiration time. Default: 900 seconds.
// Load the credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set it.
}
try {
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a GetObjectRequest object to download the object.
$request = new Oss\Models\GetObjectRequest(bucket:$bucket, key:$key);
// Call the presign method to generate a signed URL and set the expiration time.
$result = $client->presign($request, [
'expires' => new \DateInterval("PT{$expire}S") // PT stands for Period Time, and S stands for seconds.
]);
// Output the signed URL.
echo "Signed URL: " . $result->url . PHP_EOL;
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . PHP_EOL;
exit(1);
}.NET
SDK の詳細については、「.NET で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Obtain a credential from the 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Specify the V4 signature.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
var metadata = client.GetObjectMetadata(bucketName, objectName);
var etag = metadata.ETag;
// Generate a presigned URL.
var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
{
// Set the validity period of the presigned URL. Default value: 3600. Unit: seconds.
Expiration = DateTime.UtcNow.AddHours(1),
};
var uri = client.GeneratePresignedUri(req);
// Print the generated presigned URL
Console.WriteLine("Generated Signed URL: " + uri);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}Android
SDK の詳細については、「Android で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
// バケット名を指定します。例:examplebucket。
String bucketName = "examplebucket";
// ソースオブジェクトの完全なパスを、バケット名なしで指定します。例:exampleobject.txt。
String objectKey = "exampleobject.txt";
String url = null;
try {
// ファイルをダウンロードするための署名付き URL を生成します。
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
// 署名付き URL の有効期限を 30 分に設定します。
request.setExpiration(30*60);
request.setMethod(HttpMethod.GET);
url = oss.presignConstrainedObjectURL(request);
Log.d("url", url);
} catch (ClientException e) {
e.printStackTrace();
}iOS
SDK の詳細については、「iOS で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
// バケットの名前を指定します。
NSString *bucketName = @"examplebucket";
// オブジェクトの名前を指定します。
NSString *objectKey = @"exampleobject.txt";
__block NSString *urlString;
// オブジェクトをダウンロードするための有効期間付きの署名付き URL を生成します。この例では、URL の有効期間は 30 分です。
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;
}];C++
SDK の詳細については、「C++ で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. * /
std::string Region = "yourRegion";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string GetobjectUrlName = "exampledir/exampleobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* 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. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Specify the validity period of the pre-signed URL. The maximum validity period is 32,400. Unit: seconds. */
std::time_t t = std::time(nullptr) + 1200;
/* Generate a pre-signed URL. */
auto genOutcome = client.GeneratePresignedUrl(BucketName, GetobjectUrlName, t, Http::Get);
if (genOutcome.isSuccess()) {
std::cout << "GeneratePresignedUrl success, Gen url:" << genOutcome.result().c_str() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "GeneratePresignedUrl fail" <<
",code:" << genOutcome.error().Code() <<
",message:" << genOutcome.error().Message() <<
",requestId:" << genOutcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}Ruby
SDK の詳細については、「Ruby で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# The China (Hangzhou) endpoint is used as an example. Specify the endpoint based on your actual region.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Generate a presigned URL and set its validity period to 1 hour (3600 seconds).
puts bucket.object_url('my-object', true, 3600)C
SDK の詳細については、「C で署名付き URL を使用してオブジェクトをダウンロードする」をご参照ください。
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the full path of the local file. */
const char *local_filename = "yourLocalFilename";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Initialize the aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
options->config->is_cname = 0;
/* Set network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool (pool) for memory management, which is equivalent to apr_pool_t. Its implementation code is in the APR library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client option oss_client_options. */
init_options(oss_client_options);
/* Initialize parameters. */
aos_string_t bucket;
aos_string_t object;
aos_string_t file;
aos_http_request_t *req;
apr_time_t now;
char *url_str;
aos_string_t url;
int64_t expire_time;
int one_hour = 3600;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
aos_str_set(&file, local_filename);
expire_time = now / 1000000 + one_hour;
req = aos_http_request_create(pool);
req->method = HTTP_GET;
now = apr_time_now();
/* Unit: microseconds. */
expire_time = now / 1000000 + one_hour;
/* Generate a presigned URL. */
url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
aos_str_set(&url, url_str);
printf("Temporary download URL: %s\n", url_str);
/* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}コマンドラインツール ossutil の使用
examplebucket バケット内の example.txt オブジェクトに対して、有効期間 1 時間の署名付き URL を生成します。
ossutil presign oss://examplebucket/example.txt --expires-duration 1h
ossutil を使用して署名付き URL を生成するその他の例については、「presign (署名付き URL の生成)」をご参照ください。
グラフィカル管理ツール ossbrowser の使用
ossbrowser は、コンソールでサポートされているものと同様のオブジェクトレベルの操作をサポートしています。ossbrowser のインターフェイスガイドに従って、署名付き URL を取得する操作を完了してください。ossbrowser の使用方法の詳細については、「常用操作」をご参照ください。
長期間有効なリンクの取得
署名や有効期限のないファイル URL (リンク) は、次の 2 つの方法で取得できます。
-
方法 1:ファイルを公開読み取りに設定する (非推奨)
ファイルの ACL を「公開読み取り」に設定すると、永久に有効なファイル URL を取得できます。この設定は簡単で、追加のツールは不要です。ただし、ファイルアドレスは完全に公開され、誰でもアクセスでき、悪意のあるクローラーやトラフィックの乱用の標的になりやすいです。この方法は OSS のホットリンク保護 (Referer ホワイトリスト) と併用することをお勧めしますが、ソースが公開されるリスクは依然として存在します。
-
方法 2:CDN を介して公開読み取りアクセスを提供する (推奨)
ファイルを非公開に保ち、CDN を介して公開アクセスを実装します。CDN のプライベート OSS バケットのバックツーオリジン機能を有効にすると、CDN 加速ドメイン名を通じてプライベートバケット内のすべてのリソースにアクセスできます。元の URL のプライベート認証方法は無効になります。方法 1 と比較して、OSS が直接公開されないため、セキュリティが高く、加速およびアクセス制御機能をサポートします。リンクの乱用を防ぐために、CDN のReferer ホットリンク保護とURL 署名を有効にすることをお勧めします。
長期間有効なファイル URL の構築方法
ドメイン名の種類に基づいてファイルアクセスアドレスを構築できます。
|
ドメイン名タイプ |
URL フォーマット |
例 |
|
OSS デフォルトドメイン名 |
|
たとえば、中国 (杭州) リージョンに examplebucket という名前のバケットがあり、その中に example というフォルダがあり、example.jpg というファイルが含まれているとします。
|
|
カスタムドメイン名 |
|
たとえば、中国 (杭州) リージョンの examplebucket にカスタムドメイン名 |
|
CDN 加速ドメイン名 |
|
たとえば、CDN 加速ドメイン名が |
-
<BucketName>:バケットの名前。 -
<ObjectName>:ファイルの完全なパス (例:folder/example.jpg)。 -
<Endpoint>:リージョンのエンドポイント。 -
<YourDomainName>:カスタムドメイン名。詳細については、「バケットのデフォルトドメイン名にカスタムドメイン名をアタッチする」をご参照ください。 -
<CDN accelerated domain name>:CDN 加速ドメイン名。
HTTPS プロトコルの設定
リンクプロトコルはエンドポイントによって決まります。デフォルトのエンドポイントは設定不要で、直接 HTTPS をサポートします。カスタムドメイン名を使用する場合、HTTPS プロトコルを有効にする前に、まず証明書のホスティングを完了する必要があります。
-
OSS コンソール:リンクを生成する際、詳細パネルでプロトコルを選択できます。HTTPS がデフォルトのプロトコルです。
-
ossutil/SDK:設定したエンドポイントに依存します。
https://で始まる場合は HTTPS が使用されます。
.txt ファイルプレビュー時の中国語の文字化け
ブラウザや OSS コンソールで .txt ファイルをプレビューする際に、中国語の文字が文字化けして表示される場合、通常はファイルが正しいエンコード形式を宣言していないことが原因です。ファイルメタデータの Content-Type フィールドを text/plain;charset=utf-8 に設定することで、ブラウザに正しい UTF-8 エンコーディングでコンテンツを表示させることができます。
-
OSS 管理コンソールにログインします。
-
[バケットリスト] をクリックし、対象のバケットの名前をクリックします。
-
左側のナビゲーションウィンドウで、 を選択します。
-
対象オブジェクトの右側で、 を選択します。
-
[HTTP 標準プロパティ] エリアで、[Content-Type] を text/plain;charset=utf-8 に設定します。
-
[OK] をクリックして設定を保存します。
アクセス元の制限
Referer ホットリンク保護を設定することで、指定したウェブサイトのみが OSS リソースにアクセスできるようにし、他のソースからのリクエストを拒否できます。
たとえば、公式ウェブサイト https://example.com からのアクセスリクエストのみを許可し、他のソースからのリクエストは拒否することができます。
第三者への追加操作の権限付与
署名付き URL に加えて、Alibaba Cloud はより柔軟な一時的な権限付与方法である STS 一時アクセス認証情報を提供しています。第三者にダウンロード以外の操作 (リスト表示やコピーなど) を実行させたい場合は、STS 一時アクセス認証情報について学び、使用することをお勧めします。詳細については、「STS 一時アクセス認証情報で OSS にアクセスする」をご参照ください。
画像処理
画像処理パラメーターを含む署名付き URL を生成して、画像のサイズ変更やウォーターマークの追加などの画像処理を行うことができます。