Qwen-VL などのマルチモーダルモデルに画像、動画、音声を入力するには、ファイル URL が必要です。パブリック URL をお持ちでない場合、Model Studio は無料の一時ストレージを提供します。ファイルをアップロードすると、48 時間有効な oss:// URL を取得できます。
一時的な URL は、開発とテスト専用です。本番、高同時実行シナリオ、ストレステストには使用しないでください。本番ワークロードでは、長期的な可用性を確保し、レート制限を回避するため、Object Storage Service (OSS) を使用してください。
この機能は、China (Beijing) リージョンでのみ利用可能です。このリージョンの API キー を使用してください。
仕組み
ファイルをアップロードし、ターゲットモデルを指定します。API は
oss://URL を返します。モデル呼び出しの際にその URL を渡します。一時 URL を使用するには、このステップ 2 を完了する必要があります。スキップするとエラーが発生します。 HTTP 呼び出しの場合は、ヘッダー
X-DashScope-OssResourceResolve: enableを追加します。DashScope SDK では、このヘッダーが自動的に追加されます。
制限
制約 | 詳細 |
ファイルとモデルのバインディング | アップロード時にモデル名を指定します。以降の呼び出しでも同じモデルを使用してください。ファイルはモデル間で共有できません。 |
ファイルサイズの制限 | ファイルサイズは 1 GB を超えないようにし、選択したモデルの個別の制限にも準拠してください。 |
ファイルとアカウントのバインディング | アップロードとモデルの呼び出しには、同じ Alibaba Cloud アカウントの API キーを使用してください。ファイルはアカウント間で共有できません。 |
48 時間の有効期限 | ファイルは 48 時間後に自動的に削除されます。この期間内にモデルの呼び出しを完了してください。 |
アップロード後の管理なし | ファイルはクエリ、変更、ダウンロードできません。モデルの呼び出しで URL パラメーターとしてのみ使用されます。 |
レート制限 | アップロード認証情報 API は、アカウントとモデルの組み合わせごとに 100 QPS に制限されています。上限を超えるリクエストは失敗します。一時ストレージはスケールアウトをサポートしていません。 |
前提条件
開始する前に:
環境変数に設定済みの API キー
ファイルを使用するモデル名 (例:
qwen-vl-plus)
ステップ 1: 一時的な URL を取得する
次のいずれかの方法でファイルをアップロードし、一時的な URL を取得します。
コードを使用したアップロード
Python
前提条件
Python 3.8 以降
依存関係をインストールしてください。
pip install -U requestsパラメーター
パラメーター | 説明 | 例 |
| Model Studio の API キー |
|
| ファイルを使用するモデル |
|
| ローカルファイルのパス |
|
サンプルコード
import os
import requests
from pathlib import Path
from datetime import datetime, timedelta
def get_upload_policy(api_key, model_name):
"""ファイルアップロード用の認証情報を取得します。"""
url = "https://dashscope-intl.aliyuncs.com/api/v1/uploads"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
params = {
"action": "getPolicy",
"model": model_name
}
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
raise Exception(f"Failed to get upload policy: {response.text}")
return response.json()['data']
def upload_file_to_oss(policy_data, file_path):
"""ファイルを一時 OSS ストレージにアップロードします。"""
file_name = Path(file_path).name
key = f"{policy_data['upload_dir']}/{file_name}"
with open(file_path, 'rb') as file:
files = {
'OSSAccessKeyId': (None, policy_data['oss_access_key_id']),
'Signature': (None, policy_data['signature']),
'policy': (None, policy_data['policy']),
'x-oss-object-acl': (None, policy_data['x_oss_object_acl']),
'x-oss-forbid-overwrite': (None, policy_data['x_oss_forbid_overwrite']),
'key': (None, key),
'success_action_status': (None, '200'),
'file': (file_name, file)
}
response = requests.post(policy_data['upload_host'], files=files)
if response.status_code != 200:
raise Exception(f"Failed to upload file: {response.text}")
return f"oss://{key}"
def upload_file_and_get_url(api_key, model_name, file_path):
"""ファイルをアップロードして URL を取得します。"""
# 1. アップロード認証情報を取得します (100 QPS のレート制限があります)
policy_data = get_upload_policy(api_key, model_name)
# 2. ファイルを OSS にアップロードします
oss_url = upload_file_to_oss(policy_data, file_path)
return oss_url
# 使用例
if __name__ == "__main__":
# 環境変数から API キーを読み取ります
api_key = os.getenv("DASHSCOPE_API_KEY")
if not api_key:
raise Exception("Set the DASHSCOPE_API_KEY environment variable.")
# モデル名を設定します
model_name="qwen-vl-plus"
# 実際のファイルパスに置き換えてください
file_path = "/tmp/cat.png"
try:
public_url = upload_file_and_get_url(api_key, model_name, file_path)
expire_time = datetime.now() + timedelta(hours=48)
print(f"File uploaded successfully. URL valid for 48 hours.")
print(f"Expiration time: {expire_time.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Temporary URL: {public_url}")
print("Note: When you use a temporary URL with the oss:// prefix, you must add the X-DashScope-OssResourceResolve: enable parameter to the HTTP request header. For more information, see https://www.alibabacloud.com/help/model-studio/get-temporary-file-url#http-call")
except Exception as e:
print(f"Error: {str(e)}")出力例
File uploaded successfully. URL valid for 48 hours.
有効期限:2024-07-18 17:36:15
Temporary URL: oss://dashscope-instant/xxx/2024-07-18/xxx/cat.png
Note: When you use a temporary URL with the oss:// prefix, you must add the X-DashScope-OssResourceResolve: enable parameter to the HTTP request header. For more information, see https://www.alibabacloud.com/help/model-studio/get-temporary-file-url#http-call一時的な URL を取得した後、呼び出しを行う際には、HTTP リクエストに X-DashScope-OssResourceResolve: enable ヘッダーを追加してください。詳細については、「HTTP を使用した呼び出し」をご参照ください。
Java
前提条件
JDK 1.8 以降
pom.xmlに次の依存関係を追加してください。
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>パラメーター
パラメーター | 説明 | 例 |
| Model Studio の API キー |
|
| ファイルを使用するモデル |
|
| ローカルファイルのパス |
|
サンプルコード
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class PublicUrlHandler {
private static final String API_URL = "https://dashscope-intl.aliyuncs.com/api/v1/uploads";
public static JSONObject getUploadPolicy(String apiKey, String modelName) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(API_URL);
httpGet.addHeader("Authorization", "Bearer " + apiKey);
httpGet.addHeader("Content-Type", "application/json");
String query = String.format("action=getPolicy&model=%s", modelName);
httpGet.setURI(httpGet.getURI().resolve(httpGet.getURI() + "?" + query));
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
if (response.getStatusLine().getStatusCode() != 200) {
throw new IOException("Failed to get upload policy: " +
EntityUtils.toString(response.getEntity()));
}
String responseBody = EntityUtils.toString(response.getEntity());
return new JSONObject(responseBody).getJSONObject("data");
}
}
}
public static String uploadFileToOSS(JSONObject policyData, String filePath) throws IOException {
Path path = Paths.get(filePath);
String fileName = path.getFileName().toString();
String key = policyData.getString("upload_dir") + "/" + fileName;
HttpPost httpPost = new HttpPost(policyData.getString("upload_host"));
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("OSSAccessKeyId", policyData.getString("oss_access_key_id"));
builder.addTextBody("Signature", policyData.getString("signature"));
builder.addTextBody("policy", policyData.getString("policy"));
builder.addTextBody("x-oss-object-acl", policyData.getString("x_oss_object_acl"));
builder.addTextBody("x-oss-forbid-overwrite", policyData.getString("x_oss_forbid_overwrite"));
builder.addTextBody("key", key);
builder.addTextBody("success_action_status", "200");
byte[] fileContent = Files.readAllBytes(path);
builder.addBinaryBody("file", fileContent, ContentType.DEFAULT_BINARY, fileName);
httpPost.setEntity(builder.build());
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Failed to upload file: " +
EntityUtils.toString(response.getEntity()));
}
return "oss://" + key;
}
}
public static String uploadFileAndGetUrl(String apiKey, String modelName, String filePath) throws IOException {
JSONObject policyData = getUploadPolicy(apiKey, modelName);
return uploadFileToOSS(policyData, filePath);
}
public static void main(String[] args) {
// 環境変数から API キーを読み取ります
String apiKey = System.getenv("DASHSCOPE_API_KEY");
if (apiKey == null || apiKey.isEmpty()) {
System.err.println("Set the DASHSCOPE_API_KEY environment variable.");
System.exit(1);
}
// モデル名
String modelName = "qwen-vl-plus";
// 実際のファイルパスに置き換えてください
String filePath = "src/main/resources/tmp/cat.png";
try {
// ファイルが存在するか確認します
File file = new File(filePath);
if (!file.exists()) {
System.err.println("File does not exist: " + filePath);
System.exit(1);
}
String publicUrl = uploadFileAndGetUrl(apiKey, modelName, filePath);
LocalDateTime expireTime = LocalDateTime.now().plusHours(48);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("File uploaded successfully. URL valid for 48 hours.");
System.out.println("Expiration time: " + expireTime.format(formatter));
System.out.println("Temporary URL: " + publicUrl);
System.out.println("Note: When you use a temporary URL with the oss:// prefix, you must add the X-DashScope-OssResourceResolve: enable parameter to the HTTP request header. For more information, see https://www.alibabacloud.com/help/model-studio/get-temporary-file-url#http-call");
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}出力例
File uploaded successfully. URL valid for 48 hours.
有効期限:2024-07-18 17:36:15
Temporary URL: oss://dashscope-instant/xxx/2024-07-18/xxx/cat.png
Note: When you use a temporary URL with the oss:// prefix, you must add the X-DashScope-OssResourceResolve: enable parameter to the HTTP request header. For more information, see https://www.alibabacloud.com/help/model-studio/get-temporary-file-url#http-call一時的な URL を取得した後、呼び出しを行う際には、HTTP リクエストに X-DashScope-OssResourceResolve: enable ヘッダーを追加してください。詳細については、「HTTP を使用した呼び出し」をご参照ください。
CLI を使用したアップロード
DashScope CLI では、単一のコマンドでファイルをアップロードし、一時的な URL を返します。
前提条件
Python 3.8 以降
DashScope Python SDK バージョン
1.24.0以降:
pip install -U dashscopeCLI パラメーター
パラメーター | 必須 | 説明 | 例 |
| はい | ファイルアップロード用の DashScope サブコマンド |
|
| はい | ファイルの対象モデル |
|
| はい | ローカルファイルのパス (相対パスまたは絶対パス) |
|
| いいえ | API キー。 |
|
環境変数を使用したアップロード (推奨)
前提条件: API キーを環境変数として設定します。
dashscope oss.upload --model qwen-vl-plus --file cat.png出力例:
Start oss.upload: model=qwen-vl-plus, file=cat.png, api_key=None
Uploaded oss url: oss://dashscope-instant/xxx/2024-07-18/xxx/cat.pngインライン API キーを使用したアップロード
dashscope oss.upload --model qwen-vl-plus --file cat.png --api_key sk-xxxxxxx出力例:
Start oss.upload: model=qwen-vl-plus, file=cat.png, api_key=sk-xxxxxxx
Uploaded oss url: oss://dashscope-instant/xxx/2024-07-18/xxx/cat.png一時的な URL を取得した後、呼び出しを行う際には、HTTP リクエストに X-DashScope-OssResourceResolve: enable ヘッダーを追加してください。詳細については、「HTTP を使用した呼び出し」をご参照ください。
ステップ2:一時的な URL を使用したモデルの呼び出し
ファイルをアップロードした後、モデルの呼び出しには oss:// URL を使用します。次の2つのルールが適用されます。
モデルの一貫性: アップロード時に指定したものと同じモデルを使用します。
アカウントの一貫性: 同じ Alibaba Cloud アカウントの API キーを使用します。
次のいずれかの方法を選択してください。
HTTP
HTTP 経由で API を呼び出す場合 (curl、Postman など) 、次のヘッダーを追加してください。
X-DashScope-OssResourceResolve: enableこのヘッダーがない場合、API は oss:// URL を解決できず、リクエストは失敗します。
リクエスト例
この例では、qwen-vl-plus を呼び出して、アップロードされた画像を説明させます。
oss://... を実際の一時的な URL に置き換えてください。curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-DashScope-OssResourceResolve: enable' \
-d '{
"model": "qwen-vl-plus",
"messages": [{
"role": "user",
"content":
[{"type": "text","text": "What is this?"},
{"type": "image_url","image_url": {"url": "oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.png"}}]
}]
}'レスポンス例
{
"choices": [
{
"message": {
"content": "This is a picture of a white cat running on the grass. The cat has blue eyes and looks very cute and lively. The background is a blurred natural landscape, which emphasizes the subject: the small cat dashing forward. This photographic technique is called shallow depth of field (or a large aperture effect). It makes the cat in the foreground sharp and clear while blurring the background to highlight the subject and create a dreamlike effect. Overall, this photo feels relaxed and pleasant, and it captures a great moment of the animal's behavior.",
"role": "assistant"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 1253,
"completion_tokens": 104,
"total_tokens": 1357
},
"created": 1739349052,
"system_fingerprint": null,
"model": "qwen-vl-plus",
"id": "chatcmpl-cfc4f2aa-22a8-9a94-8243-44c5bd9899bc"
}DashScope SDK
DashScope SDK は X-DashScope-OssResourceResolve ヘッダーを自動的に処理します。oss:// URL をファイルパラメーターとして直接渡してください。
OpenAI SDK はサポートされていません。すべてのモデルが SDK の呼び出しをサポートしているわけではありません。詳細については、特定のモデルの API リファレンスをご参照ください。
Python
前提条件: DashScope Python SDK 1.24.0 以降。
この例では、qwen-vl-plus を呼び出して、アップロードされた画像を説明させます。このコードは qwen-vl および omni モデルに適用できます。
image パラメーターの oss://... を実際の一時的な URL に置き換えてください。import os
import dashscope
messages = [
{
"role": "system",
"content": [{"text": "You are a helpful assistant."}]
},
{
"role": "user",
"content": [
{"image": "oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.png"},
{"text": "What is this?"}]
}]
# 環境変数として設定されていない場合は、api_key="sk-xxx" に置き換えてください
api_key = os.getenv('DASHSCOPE_API_KEY')
response = dashscope.MultiModalConversation.call(
api_key=api_key,
model='qwen-vl-plus',
messages=messages
)
print(response)レスポンス例
{
"status_code": 200,
"request_id": "ccd9dcfb-98f0-92bc-xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"text": "This is a photo of a cat running on the grass. The cat's fur is mainly white with light brown spots, and its eyes are blue, making it look very cute. The background is a blurry green meadow with some trees, and the sunlight adds a warm feeling to the whole picture. The cat's posture shows that it is moving quickly, possibly chasing something or just enjoying the outdoors. Overall, this is a vibrant and lively picture."
}
]
}
}
]
},
"usage": {
"input_tokens": 1112,
"output_tokens": 91,
"input_tokens_details": {
"text_tokens": 21,
"image_tokens": 1091
},
"prompt_tokens_details": {
"cached_tokens": 0
},
"total_tokens": 1203,
"output_tokens_details": {
"text_tokens": 91
},
"image_tokens": 1091
}
}Java
前提条件: DashScope Java SDK 2.21.0 以降。
この例では、qwen-vl-plus を呼び出して、アップロードされた画像を説明させます。このコードは qwen-vl および omni モデルに適用できます。
oss://... を実際の一時的な URL に置き換えてください。import com.alibaba.dashscope.aigc.multimodalconversation.*;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Arrays;
public class MultiModalConversationUsage {
private static final String modelName = "qwen-vl-plus";
// 環境変数として設定されていない場合は、api_key="sk-xxx" に置き換えてください
public static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void simpleMultiModalConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessageItemText systemText = new MultiModalMessageItemText("You are a helpful assistant.");
MultiModalConversationMessage systemMessage = MultiModalConversationMessage.builder()
.role(Role.SYSTEM.getValue()).content(Arrays.asList(systemText)).build();
MultiModalMessageItemImage userImage = new MultiModalMessageItemImage(
"oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.png");
MultiModalMessageItemText userText = new MultiModalMessageItemText("What is this?");
MultiModalConversationMessage userMessage =
MultiModalConversationMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(userImage, userText)).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
.model(MultiModalConversationUsage.modelName)
.apiKey(apiKey)
.message(systemMessage)
.vlHighResolutionImages(true)
.vlEnableImageHwOutput(true)
// .incrementalOutput(true)
.message(userMessage).build();
MultiModalConversationResult result = conv.call(param);
System.out.print(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
simpleMultiModalConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}レスポンス例
{
"requestId": "b6d60f91-4a7f-9257-xxxxxx",
"usage": {
"input_tokens": 1112,
"output_tokens": 91,
"total_tokens": 1203,
"image_tokens": 1091,
"input_tokens_details": {
"text_tokens": 21,
"image_tokens": 1091
},
"output_tokens_details": {
"text_tokens": 91
}
},
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"text": "This is a photo of a cat running on the grass. The cat's fur is mainly white with light brown spots, and its eyes are blue, making it look very cute. The background is a blurry green meadow with some trees, and the sunlight adds a warm feeling to the whole picture. The cat's posture shows that it is moving quickly, possibly chasing something or just enjoying the outdoors. Overall, this is a vibrant and lively picture."
},
{
"image_hw": [
[
"924",
"924"
]
]
}
]
}
}
]
}
}API リファレンス
ステップ 1 のコードサンプルと CLI は、内部で次の 3 つの API を呼び出します。このリファレンスを使用して、アップロードフローを手動で実装できます。
ファイルアップロード認証情報の取得
GET https://dashscope.aliyuncs.com/api/v1/uploads認証情報 API は、アカウントごと、モデルごとに 100 QPS のレート制限があります。一時ストレージはスケールアウトできません。本番環境または高同時実行性ワークロードでは、Alibaba Cloud OSS を使用してください。
リクエストパラメーター
Location | Field | Type | Required | Description | Example |
Header | Content-Type | string | Yes | リクエストのタイプです。 |
|
Header | Authorization | string | Yes | Model Studio の API キーです。 |
|
Params | action | string | Yes | 操作タイプです。 |
|
Params | model | string | Yes | ターゲットモデル名です。 |
|
レスポンスパラメーター
Field | Type | Description | Example |
request_id | string | 一意のリクエスト ID です。 |
|
data | object | - | - |
data.policy | string | アップロード認証情報です。 |
|
data.signature | string | 認証情報署名です。 |
|
data.upload_dir | string | アップロードディレクトリのパスです。 |
|
data.upload_host | string | アップロード先の OSS ホストです。 |
|
data.expire_in_seconds | number | 認証情報の有効期間 (秒) です。有効期限が切れた場合は、新しい認証情報を取得してください。 |
|
data.max_file_size_mb | number | アップロードできる最大ファイルサイズ (MB) です。モデルによって異なります。 |
|
data.capacity_limit_mb | number | Alibaba Cloud アカウントあたりの 1 日のアップロード容量 (MB) です。 |
|
data.oss_access_key_id | string | アップロード用のアクセスキーです。 |
|
data.x_oss_object_acl | string | アップロードしたファイルのアクセス権限です。 |
|
data.x_oss_forbid_overwrite | string | 同名ファイルの上書きをブロックするかどうかを指定します。 |
|
サンプルリクエスト
curl --location 'https://dashscope.aliyuncs.com/api/v1/uploads?action=getPolicy&model=qwen-vl-plus' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json'API キーが環境変数として設定されていない場合は、$DASHSCOPE_API_KEYをお使いの API キーに置き換えてください:--header "Authorization: Bearer sk-xxx"。
サンプルレスポンス
{
"request_id": "52f4383a-c67d-9f8c-xxxxxx",
"data": {
"policy": "eyJl...1ZSJ=",
"signature": "eWy...=",
"upload_dir": "dashscope-instant/xxx/2024-07-18/xxx",
"upload_host": "https://dashscope-file-xxx.oss-cn-beijing.aliyuncs.com",
"expire_in_seconds": 300,
"max_file_size_mb": 100,
"capacity_limit_mb": 999999999,
"oss_access_key_id": "LTA...",
"x_oss_object_acl": "private",
"x_oss_forbid_overwrite": "true"
}
}一時ストレージへのファイルアップロード
POST {data.upload_host}{data.upload_host}は、認証情報レスポンスのdata.upload_hostに置き換えてください。
リクエストパラメーター
Location | Field | Type | Required | Description | Example |
Header | Content-Type | string | No |
|
|
form-data | OSSAccessKeyId | text | Yes | 認証情報レスポンスの |
|
form-data | policy | text | Yes | 認証情報レスポンスの |
|
form-data | Signature | text | Yes | 認証情報レスポンスの |
|
form-data | key | text | Yes | 認証情報レスポンスの |
|
form-data | x-oss-object-acl | text | Yes | 認証情報レスポンスの |
|
form-data | x-oss-forbid-overwrite | text | Yes | 認証情報レスポンスの |
|
form-data | success_action_status | text | No | 成功時に返される HTTP ステータスコードです。通常は |
|
form-data | file | file | Yes | アップロードするファイルです。1 リクエストあたり 1 ファイルのみです。 |
|
成功すると、API は HTTP 200 を返しますが、レスポンスボディはありません。
サンプルリクエスト
curl --location 'https://dashscope-file-xxx.oss-cn-beijing.aliyuncs.com' \
--form 'OSSAccessKeyId="LTAm5xxx"' \
--form 'Signature="Sm/tv7DcZuTZftFVvt5yOoSETsc="' \
--form 'policy="eyJleHBpcmF0aW9 ... ... ... dHJ1ZSJ9XX0="' \
--form 'x-oss-object-acl="private"' \
--form 'x-oss-forbid-overwrite="true"' \
--form 'key="dashscope-instant/xxx/2024-07-18/xxx/cat.png"' \
--form 'success_action_status="200"' \
--form 'file=@"/tmp/cat.png"'ファイルURLの構築
oss:// と、アップロードリクエストの key を連結します。この URL は 48 時間有効です。
oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.pngエラーコード
API 呼び出しが失敗した場合、一般的なトラブルシューティングについてはエラーメッセージをご参照ください。
以下のエラーコードは、一時ファイルのアップロードに固有のものです。
HTTP ステータス | エラーコード | エラーメッセージ | 原因と解決策 |
400 | invalid_parameter_error | InternalError.Algo.InvalidParameter: The provided URL does not appear to be valid. Ensure it is correctly formatted. | URL が不正な形式です。URL の形式を確認してください。HTTP 経由で |
400 | InvalidParameter.DataInspection | The media format is not supported or incorrect for the data inspection. | リクエストヘッダーに |
403 | AccessDenied | Invalid according to Policy: Policy expired. | アップロード認証情報の有効期限が切れています。認証情報 API を再度呼び出して、新しい認証情報を取得してください。 |
429 | Throttling.RateQuota | Requests rate limit exceeded, please try again later. | リクエストレートが 100 QPS を超えています。リクエスト頻度を減らすか、本番ワークロードの場合はOSSに移行してください。 |
よくある質問
oss:// URL でエラーが返される場合はどうすればよいですか?
次の手順に従ってください:
リクエストヘッダーを確認してください。 HTTP (curl、Postmanなど) 経由で API を呼び出す場合は、リクエストヘッダーに
X-DashScope-OssResourceResolve: enableを追加してください。このヘッダーがないと、サーバーはoss://プロトコルを解決できません。DashScope SDK はこのヘッダーを自動的に追加します。URLの有効性を確認してください。
oss://URL は、アップロードから48時間後に有効期限が切れます。有効期限が切れている場合は、ファイルを再度アップロードして新しい URL を取得してください。
ファイルのアップロードとモデルの呼び出しで異なる API キーを使用できますか?
はい、両方の API キーが同じ Alibaba Cloud アカウントに属している場合に限り使用できます。ファイルアクセスは API キーレベルではなく、アカウントレベルで管理されます。
異なる Alibaba Cloud アカウントの API キーでは、相互にアップロードされたファイルへアクセスできません。