デフォルトでは、Object Storage Service (OSS) バケット内のオブジェクトのアクセス制御リスト (ACL) は非公開に設定されています。 つまり、オブジェクト所有者のみがオブジェクトにアクセスできます。 このトピックでは、OSS SDK for PHP を使用して、HTTP PUT メソッドを使用して指定された期間内に特定のオブジェクトをユーザーがアップロードできるようにする署名付き URL を生成する方法について説明します。 有効期間内は、ユーザーは署名付き URL を使用してオブジェクトに繰り返しアクセスできます。 署名付き URL の有効期限が切れた場合は、署名付き URL を再生成して、ユーザーのアクセスを延長できます。
注意事項
このトピックのサンプルコードでは、中国 (杭州) リージョンのリージョン ID
cn-hangzhouを使用しています。 デフォルトでは、パブリックエンドポイントを使用してバケット内のリソースにアクセスします。 バケットが配置されているのと同じリージョン内の他の Alibaba Cloud サービスからバケット内のリソースにアクセスする場合は、内部エンドポイントを使用します。 サポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。署名付き URL を生成するために特定の権限は必要ありません。 ただし、サードパーティが署名付き URL を使用してオブジェクトをアップロードできるようにするには、
oss:PutObject権限が必要です。 詳細については、「カスタムポリシーを使用して RAM ユーザーに権限を付与する」をご参照ください。このトピックでは、署名アルゴリズム V4 を使用して、最長 7 日間の有効期間を持つ署名付き URL を生成します。 詳細については、「(推奨) URL に V4 署名を含める」をご参照ください。
このトピックでは、アクセス認証情報は環境変数から取得されます。 詳細については、「OSS SDK for PHP のアクセス認証情報を構成する」をご参照ください。
プロセス
次の図は、HTTP PUT リクエストを許可する署名付き URL を使用してオブジェクトを OSS にアップロードする方法を示しています。
サンプルコード
オブジェクト所有者は、HTTP PUT リクエストを許可する署名付き URL を生成します。
重要HTTP PUT リクエストを許可する署名付き URL を生成するときにリクエストヘッダーを指定する場合は、署名付き URL を使用して開始された PUT リクエストにリクエストヘッダーが含まれていることを確認してください。 これにより、リクエストの失敗と署名エラーを防ぎます。
<?php // Include the autoload file to load dependencies. require_once __DIR__ . '/../vendor/autoload.php'; use AlibabaCloud\Oss\V2 as Oss; // Define and describe command-line options. $optsdesc = [ "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located. "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint for accessing OSS. "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket. "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object. ]; // Convert the descriptions to a list of long options required by getopt. // Add a colon (:) to the end of each option to indicate that a value is required. $longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc)); // Parse the command-line options. $options = getopt("", $longopts); // Check whether required options are missing. foreach ($optsdesc as $key => $value) { if ($value['required'] === True && empty($options[$key])) { $help = $value['help']; // Obtain help information. echo "Error: the following arguments are required: --$key, $help" . PHP_EOL; exit(1); // Exit the program if a required option is missing. } } // Assign the values parsed from the command-line options to the corresponding variables. $region = $options["region"]; // The region in which the bucket is located. $bucket = $options["bucket"]; // The name of the bucket. $key = $options["key"]; // The name of the object // Load access credentials from environment variables. // Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables. $credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Use the default configuration of the SDK. $cfg = Oss\Config::loadDefault(); $cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider. $cfg->setRegion($region); // Specify the region in which the bucket is located. if (isset($options["endpoint"])) { $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided. } // Create an OSS client instance. $client = new Oss\Client($cfg); // Create a PutObjectRequest object to upload the data. $request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key); // Call the presign method to generate a presigned request. $result = $client->presign($request); // Display the result of the presign operation. // Display the presigned URL, which can be used to upload the specified object. print( 'put object presign result:' . var_export($result, true) . PHP_EOL . // The details of the presign result. 'put object url:' . $result->url . PHP_EOL // The presigned URL. );ユーザーは署名付き URL を使用してオブジェクトをアップロードします。
curl
curl -X PUT -T /path/to/local/file "https://exampleobject.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T083238Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************%2F20241112%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=ed5a******************************************************"Java
import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.*; import java.net.URL; import java.util.*; public class SignUrlUpload { public static void main(String[] args) throws Throwable { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; // <signedUrl> を承認 URL に置き換えます。 URL signedUrl = new URL("<signedUrl>"); // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 String pathName = "C:\\Users\\demo.txt"; try { HttpPut put = new HttpPut(signedUrl.toString()); System.out.println(put); HttpEntity entity = new FileEntity(new File(pathName)); put.setEntity(entity); httpClient = HttpClients.createDefault(); response = httpClient.execute(put); System.out.println("Status code returned:"+response.getStatusLine().getStatusCode()); if(response.getStatusLine().getStatusCode() == 200){ System.out.println("Uploaded successfully using the network library."); } System.out.println(response.toString()); } catch (Exception e){ e.printStackTrace(); } finally { response.close(); httpClient.close(); } } }Go
package main import ( "fmt" "io" "net/http" "os" ) func uploadFile(signedUrl, filePath string) error { // ファイルを開きます。 file, err := os.Open(filePath) if err != nil { return fmt.Errorf("ファイルを開けませんでした: %w", err) } defer file.Close() // 新しい HTTP クライアントを作成します。 client := &http.Client{} // PUT リクエストを作成します。 req, err := http.NewRequest("PUT", signedUrl, file) if err != nil { return fmt.Errorf("リクエストの作成に失敗しました: %w", err) } // リクエストを送信します。 resp, err := client.Do(req) if err != nil { return fmt.Errorf("リクエストの送信に失敗しました: %w", err) } defer resp.Body.Close() // レスポンスを読み取ります。 body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("レスポンスの読み取りに失敗しました: %w", err) } fmt.Printf("Status code returned: %d\n", resp.StatusCode) if resp.StatusCode == 200 { fmt.Println("Uploaded successfully using the network library.") } fmt.Println(string(body)) return nil } func main() { // <signedUrl> を承認 URL に置き換えます。 signedUrl := "<signedUrl>" // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 filePath := "C:\\Users\\demo.txt" err := uploadFile(signedUrl, filePath) if err != nil { fmt.Println("An error occurred:", err) } }python
import requests def upload_file(signed_url, file_path): try: # ファイルを開きます。 with open(file_path, 'rb') as file: # PUT リクエストを送信してファイルをアップロードします。 response = requests.put(signed_url, data=file) print(f"Status code returned: {response.status_code}") if response.status_code == 200: print("Uploaded successfully using the network library.") print(response.text) except Exception as e: print(f"An error occurred: {e}") if __name__ == "__main__": # <signedUrl> を承認 URL に置き換えます。 signed_url = "<signedUrl>" // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 file_path = "C:\\Users\\demo.txt" upload_file(signed_url, file_path)Node.js
const fs = require('fs'); const axios = require('axios'); async function uploadFile(signedUrl, filePath) { try { // 読み取りストリームを作成します。 const fileStream = fs.createReadStream(filePath); // PUT リクエストを送信してファイルをアップロードします。 const response = await axios.put(signedUrl, fileStream, { headers: { 'Content-Type': 'application/octet-stream' // 要件に基づいて Content-Type を調整します。 } }); console.log(`Status code returned: ${response.status}`); if (response.status === 200) { console.log('Uploaded successfully using the network library.'); } console.log(response.data); } catch (error) { console.error(`An error occurred: ${error.message}`); } } // メイン関数。 (async () => { // <signedUrl> を承認 URL に置き換えます。 const signedUrl = '<signedUrl>'; // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 const filePath = 'C:\\Users\\demo.txt'; await uploadFile(signedUrl, filePath); })();browser.js
重要Browser.js を使用してファイルをアップロードし、403 SignatureDoesNotMatch エラーが発生した場合、通常、ブラウザが Content-Type リクエストヘッダーを自動的に追加するためにエラーが発生します。 署名付き URL の生成時にこのヘッダーが指定されていない場合、署名の検証は失敗します。 この問題を解決するには、署名付き URL を生成するときに Content-Type リクエストヘッダーを指定する必要があります。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>File Upload Example</title> </head> <body> <h1>File Upload Example</h1> <!-- ファイルを選択 --> <input type="file" id="fileInput" /> <button id="uploadButton">Upload File</button> <script> // これを手順 1 で生成された署名付き URL に置き換えます。 const signedUrl = "<signedUrl>"; document.getElementById('uploadButton').addEventListener('click', async () => { const fileInput = document.getElementById('fileInput'); const file = fileInput.files[0]; if (!file) { alert('アップロードするファイルを選択してください。'); return; } try { await upload(file, signedUrl); alert('ファイルが正常にアップロードされました!'); } catch (error) { console.error('Error during upload:', error); alert('アップロードに失敗しました: ' + error.message); } }); /** * OSS にファイルをアップロードします。 * @param {File} file - アップロードするファイル。 * @param {string} presignedUrl - 署名付き URL。 */ const upload = async (file, presignedUrl) => { const response = await fetch(presignedUrl, { method: 'PUT', body: file, // ファイル全体をアップロードします。 }); if (!response.ok) { throw new Error(`Upload failed, status: ${response.status}`); } console.log('File uploaded successfully'); }; </script> </body> </html>C#
using System.Net.Http.Headers; // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 var filePath = "C:\\Users\\demo.txt"; // <signedUrl> を承認 URL に置き換えます。 var presignedUrl = "<signedUrl>"; // HTTP クライアントを作成し、ローカルファイルストリームを開きます。 using var httpClient = new HttpClient(); using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); using var content = new StreamContent(fileStream); // PUT リクエストを作成します。 var request = new HttpRequestMessage(HttpMethod.Put, presignedUrl); request.Content = content; // リクエストを送信します。 var response = await httpClient.SendAsync(request); // レスポンスを処理します。 if (response.IsSuccessStatusCode) { Console.WriteLine($"Uploaded successfully! Status code: {response.StatusCode}"); Console.WriteLine("Response header:"); foreach (var header in response.Headers) { Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}"); } } else { string responseContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Upload failed! Status code: {response.StatusCode}"); Console.WriteLine("Response content: " + responseContent); }C++
#include <iostream> #include <fstream> #include <curl/curl.h> void uploadFile(const std::string& signedUrl, const std::string& filePath) { CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { // URL を設定します。 curl_easy_setopt(curl, CURLOPT_URL, signedUrl.c_str()); // リクエストメソッドを PUT に設定します。 curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); // ファイルを開きます。 FILE *file = fopen(filePath.c_str(), "rb"); if (!file) { std::cerr << "Failed to open the file: " << filePath << std::endl; return; } // ファイルサイズを取得します。 fseek(file, 0, SEEK_END); long fileSize = ftell(file); fseek(file, 0, SEEK_SET); // ファイルサイズを設定します。 curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)fileSize); // 入力ファイルハンドルを設定します。 curl_easy_setopt(curl, CURLOPT_READDATA, file); // リクエストを実行します。 res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl; } else { long httpCode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); std::cout << "Status code returned: " << httpCode << std::endl; if (httpCode == 200) { std::cout << "Uploaded successfully using the network library." << std::endl; } } // ファイルを閉じます。 fclose(file); // クリーンアップします。 curl_easy_cleanup(curl); } curl_global_cleanup(); } int main() { // <signedUrl> を承認 URL に置き換えます。 std::string signedUrl = "<signedUrl>"; // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 std::string filePath = "C:\\Users\\demo.txt"; uploadFile(signedUrl, filePath); return 0; }Android
package com.example.signurlupload; import android.os.AsyncTask; import android.util.Log; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class SignUrlUploadActivity { private static final String TAG = "SignUrlUploadActivity"; public void uploadFile(String signedUrl, String filePath) { new UploadTask().execute(signedUrl, filePath); } private class UploadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String signedUrl = params[0]; String filePath = params[1]; HttpURLConnection connection = null; DataOutputStream dos = null; FileInputStream fis = null; try { URL url = new URL(signedUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("PUT"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); fis = new FileInputStream(filePath); dos = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) != -1) { dos.write(buffer, 0, length); } dos.flush(); dos.close(); fis.close(); int responseCode = connection.getResponseCode(); Log.d(TAG, "Status code returned: " + responseCode); if (responseCode == 200) { Log.d(TAG, "Uploaded successfully using the network library."); } return "Upload completed. Status code: " + responseCode; } catch (IOException e) { e.printStackTrace(); return "Upload failed: " + e.getMessage(); } finally { if (connection != null) { connection.disconnect(); } } } @Override protected void onPostExecute(String result) { Log.d(TAG, result); } } public static void main(String[] args) { SignUrlUploadActivity activity = new SignUrlUploadActivity(); // <signedUrl> を承認 URL に置き換えます。 String signedUrl = "<signedUrl>"; // ローカルファイルのフルパスを指定します。 ローカルパスを指定しない場合、デフォルトでは、サンプルプログラムのプロジェクトに対応するパスからファイルがアップロードされます。 String filePath = "C:\\Users\\demo.txt"; activity.uploadFile(signedUrl, filePath); } }