Los modelos multimodales como Qwen-VL requieren URL de archivos para entradas de imagen, video y audio. Model Studio proporciona almacenamiento temporal gratuito si no dispone de URL públicas: cargue un archivo y obtenga una URL oss:// válida durante 48 horas.
ImportanteLas URL temporales son solo para desarrollo y pruebas, no para producción, escenarios de alta concurrencia ni pruebas de estrés. Para cargas de trabajo de producción, utilice Object Storage Service (OSS) para garantizar disponibilidad a largo plazo y evitar límites de velocidad.
NotaEsta función está disponible en las regiones de Singapur y China (Beijing). Los ejemplos de código de este documento utilizan la región de Singapur de forma predeterminada. Para usar la región de Beijing, siga los comentarios de los ejemplos para reemplazar dashscope-intl.aliyuncs.com por dashscope.aliyuncs.com en la URL de la solicitud y utilice una clave de API de la región de Beijing (las claves de API de ambas regiones son diferentes; consulte clave de API).
Funcionamiento
- Cargue un archivo y especifique el modelo de destino. La API devuelve una URL
oss://. - Pase esa URL en su llamada al modelo. Debe completar el Paso 2 para usar la URL temporal; omitirlo provoca errores. Para llamadas HTTP, agregue el encabezado
X-DashScope-OssResourceResolve: enable. El SDK de DashScope agrega este encabezado automáticamente.
Limitaciones
Restricción | Detalle |
|---|---|
Vinculación archivo-modelo | Especifique el nombre del modelo durante la carga. Utilice el mismo modelo en llamadas posteriores; los archivos no se pueden compartir entre modelos. |
Límites de tamaño de archivo | El tamaño del archivo no debe exceder 1 GB y también debe cumplir con los límites específicos del modelo seleccionado. |
Vinculación archivo-cuenta | Las claves de API para la carga y las llamadas al modelo deben pertenecer a la misma cuenta de Alibaba Cloud; los archivos no se pueden compartir entre cuentas. |
Caducidad de 48 horas | Los archivos se eliminan automáticamente después de 48 horas. Complete las llamadas al modelo dentro de este período. |
Sin gestión posterior a la carga | Los archivos no se pueden consultar, modificar ni descargar; solo sirven como parámetros de URL en las llamadas al modelo. |
Limitación de tasa | La API de credenciales de carga está limitada a 100 QPS por cuenta y por modelo. Las solicitudes excedentes fallarán. El almacenamiento temporal no admite escalado horizontal. |
Requisitos previos
Antes de comenzar:
- Una clave de API configurada como variable de entorno
- El nombre del modelo que consumirá el archivo (por ejemplo,
qwen3-vl-plus)
Paso 1: Obtener una URL temporal
Cargue un archivo y obtenga su URL temporal mediante uno de estos métodos:
Cargar con código
Python
Requisitos previos- Python 3.9 o posterior
- Instale las dependencias:
pip install -U requests
ParámetrosParámetro | Descripción | Ejemplo |
|---|---|---|
| Clave de API de Model Studio | Leído de la variable de entorno |
| El modelo que consumirá el archivo |
|
| Ruta al archivo local |
|
import os
import requests
from pathlib import Path
from datetime import datetime, timedelta
def get_upload_policy(api_key, model_name):
"""Get the file upload credential."""
# The API keys for the Singapore and Beijing regions are different. Use the key for the corresponding region.
# The URL below is for the Singapore region. For the Beijing region, replace it with: https://dashscope.aliyuncs.com/api/v1/uploads
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):
"""Upload the file to the temporary OSS storage."""
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):
"""Upload the file and get the URL."""
# 1. Get the upload credential (rate-limited to 100 QPS)
policy_data = get_upload_policy(api_key, model_name)
# 2. Upload the file to OSS
oss_url = upload_file_to_oss(policy_data, file_path)
return oss_url
# Example
if __name__ == "__main__":
# Read the API key from the environment variable
api_key = os.getenv("DASHSCOPE_API_KEY")
if not api_key:
raise Exception("Set the DASHSCOPE_API_KEY environment variable.")
# Set the model name
model_name="qwen3-vl-plus"
# Replace with the actual file path
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)}")
Salida de ejemploFile uploaded successfully. URL valid for 48 hours.
Expiration time: 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
ImportanteDespués de obtener la URL temporal, agregue el encabezado X-DashScope-OssResourceResolve: enable a las solicitudes HTTP al realizar una llamada. Para obtener más información, consulte Llamada mediante HTTP.
Java
Requisitos previos- JDK 1.8 o posterior
- Agregue las siguientes dependencias a
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>
ParámetrosParámetro | Descripción | Ejemplo |
|---|---|---|
| Clave de API de Model Studio | Leído de la variable de entorno |
| El modelo que consumirá el archivo |
|
| Ruta al archivo local |
|
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 {
// The API keys for the Singapore and Beijing regions are different. Use the key for the corresponding region.
// The URL below is for the Singapore region. For the Beijing region, replace it with: https://dashscope.aliyuncs.com/api/v1/uploads
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) {
// Read the API key from the environment variable
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);
}
// Model name
String modelName = "qwen3-vl-plus";
// Replace with the actual file path
String filePath = "src/main/resources/tmp/cat.png";
try {
// Check if the file exists
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());
}
}
}
Salida de ejemploFile uploaded successfully. URL valid for 48 hours.
Expiration time: 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
ImportanteDespués de obtener la URL temporal, agregue el encabezado X-DashScope-OssResourceResolve: enable a las solicitudes HTTP al realizar una llamada. Para obtener más información, consulte Llamada mediante HTTP.
CLI de dashscope
Llamada a través de la línea de comandos dashscope.
export DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with your workspace ID, ap-southeast-1 with your region (e.g., us-east-1, eu-central-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# List uploaded files
dashscope files list
# Upload a local file
dashscope oss upload -f train_data.jsonl -m qwen-plus
ImportanteEl asistente interactivo SDK Expert puede realizar las mismas tareas de desarrollo y solución de problemas mediante lenguaje natural; consulte
DashScope SDK Expert.Para la tabla completa de regiones, consulte Resumen de URL base.
Cargar con la CLI
La CLI de DashScope carga un archivo con un solo comando y devuelve la URL temporal.
Requisitos previos- Python 3.9 o posterior
- SDK de Python de DashScope versión
1.24.0o posterior:
pip install -U dashscope
Parámetros de CLIParámetro | Obligatorio | Descripción | Ejemplo |
|---|---|---|---|
| Sí | Subcomando de DashScope para carga de archivos |
|
| Sí | Modelo de destino para el archivo |
|
| Sí | Ruta del archivo local (relativa o absoluta) |
|
| No | Clave de API. No es necesaria si la variable de entorno |
|
Requisito previo: Configure la clave de API como variable de entorno:
dashscope oss.upload --model qwen3-vl-plus --file cat.png
Salida de ejemplo:
Start oss.upload: model=qwen3-vl-plus, file=cat.png, api_key=None
Uploaded oss url: oss://dashscope-instant/xxxx/2025-08-01/xxxx/cat.png
Carga con una clave de API en líneadashscope oss.upload --model qwen3-vl-plus --file cat.png --api_key sk-xxxxxxx
Salida de ejemplo:
Start oss.upload: model=qwen3-vl-plus, file=cat.png, api_key=sk-xxxxxxx
Uploaded oss url: oss://dashscope-instant/xxx/2025-08-01/xxx/cat.png
ImportanteDespués de obtener la URL temporal, agregue el encabezado X-DashScope-OssResourceResolve: enable a las solicitudes HTTP al realizar una llamada. Para obtener más información, consulte Llamada mediante HTTP.
Paso 2: Llamar al modelo con la URL temporal
Después de cargar un archivo, utilice la URL oss:// en su llamada al modelo. Se aplican dos reglas:
- Consistencia del modelo: Utilice el mismo modelo que especificó durante la carga.
- Consistencia de cuenta: Utilice una clave de API que pertenezca a la misma cuenta de Alibaba Cloud.
Elija uno de estos métodos:
HTTP
Al llamar a la API a través de HTTP (curl, Postman, etc.), agregue este encabezado:
X-DashScope-OssResourceResolve: enable
Sin este encabezado, la API no puede resolver las URL oss:// y las solicitudes fallan.
Este ejemplo llama a qwen3-vl-plus para describir una imagen cargada.
Reemplace
oss://...con su URL temporal real.
# The URL below is for the Singapore region. For the Beijing region, replace it with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
curl -X POST https://dashscope-intl.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": "qwen3-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"}}]
}]
}'
Ejemplo de respuesta
{
"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": "qwen3-vl-plus",
"id": "chatcmpl-cfc4f2aa-22a8-9a94-8243-44c5bd9899bc"
}
SDK de DashScope
El SDK de DashScope maneja el encabezado X-DashScope-OssResourceResolve automáticamente; pase la URL oss:// directamente como parámetro de archivo.
El SDK de OpenAI no es compatible. No todos los modelos admiten llamadas mediante SDK; consulte la referencia de API del modelo específico para obtener más detalles.
Python
Requisito previo: SDK de Python de DashScope 1.24.0 o posterior.
Este ejemplo llama a qwen3-vl-plus para describir una imagen cargada. Este código se aplica a los modelos qwen-vl y omni.
Reemplace
oss://...en el parámetro de imagen con su URL temporal real.
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?"}]
}]
# The API keys for the Singapore and Beijing regions are different. Use the key for the corresponding region.
# If not configured as environment variable, replace with: api_key="sk-xxx"
api_key = os.getenv('DASHSCOPE_API_KEY')
# The URL below is for the Singapore region. For the Beijing region, replace it with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
response = dashscope.MultiModalConversation.call(
api_key=api_key,
model='qwen3-vl-plus',
messages=messages
)
print(response)
Ejemplo de respuesta{
"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
Requisito previo: SDK de Java de DashScope 2.21.0 o posterior.
Este ejemplo llama a qwen3-vl-plus para describir una imagen cargada. Este código se aplica a los modelos qwen-vl y omni.
Reemplace
oss://...con su URL temporal real.
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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Arrays;
public class MultiModalConversationUsage {
private static final String modelName = "qwen3-vl-plus";
// The API keys for the Singapore and Beijing regions are different. Use the key for the corresponding region.
// If not configured as environment variable, replace with: api_key="sk-xxx"
public static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void simpleMultiModalConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
// The URL below is for the Singapore region. For the Beijing region, replace it with: https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
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);
}
}
Ejemplo de respuesta{
"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"
]
]
}
]
}
}
]
}
}
Referencia de API
Los ejemplos de código y la CLI en el Paso 1 encapsulan estas tres operaciones de API internamente. Utilice esta referencia para implementar el flujo de carga manualmente.
Obtener una credencial de carga de archivos
Singapore: GET https://dashscope-intl.aliyuncs.com/api/v1/uploads
Beijing: GET https://dashscope.aliyuncs.com/api/v1/uploads
ImportanteLa API de credenciales tiene un límite de 100 QPS por cuenta y por modelo. El almacenamiento temporal no se puede escalar horizontalmente. Para cargas de trabajo de producción o de alta concurrencia, utilice Alibaba Cloud OSS.
Parámetros de solicitud
Location | Campo | Tipo | Obligatorio | Descripción | Ejemplo |
|---|---|---|---|---|---|
Header | Content-Type | _string_ | Sí | Tipo de solicitud. |
|
Header | Authorization | _string_ | Sí | Clave de API de Model Studio. |
|
Params | action | _string_ | Sí | Tipo de operación. Establezca en |
|
Params | model | _string_ | Sí | Nombre del modelo objetivo. |
|
Parámetros de respuesta
Campo | Tipo | Descripción | Ejemplo |
|---|---|---|---|
request_id | _string_ | ID único de solicitud. |
|
data | _object_ | - | - |
data.policy | _string_ | Credencial de carga. |
|
data.signature | _string_ | Firma de credencial. |
|
data.upload_dir | _string_ | Ruta del directorio de carga. |
|
data.upload_host | _string_ | Host de OSS para la carga. | |
data.expire_in_seconds | _string_ | Validez de la credencial en segundos. Obtenga una nueva credencial después de la caducidad. |
|
data.max_file_size_mb | _string_ | Tamaño máximo de archivo de carga en MB. Varía según el modelo. |
|
data.capacity_limit_mb | _string_ | Capacidad de carga diaria por cuenta de Alibaba Cloud en MB. |
|
data.oss_access_key_id | _string_ | Clave de acceso para la carga. |
|
data.x_oss_object_acl | _string_ | Permiso de acceso al archivo cargado. |
|
data.x_oss_forbid_overwrite | _string_ | Indica si se bloquea la sobrescritura de archivos con el mismo nombre. |
|
Solicitud de ejemplo
# The URL below is for the Singapore region. For the Beijing region, replace it with: https://dashscope.aliyuncs.com/api/v1/uploads
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/uploads?action=getPolicy&model=qwen3-vl-plus' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json'
Si la clave de API no está configurada como variable de entorno, reemplace
$DASHSCOPE_API_KEYcon su clave de API:--header "Authorization: Bearer sk-xxx".
Respuesta de ejemplo
{
"request_id": "52f4383a-c67d-9f8c-xxxxxx",
"data": {
"policy": "eyJl...1ZSJ=",
"signature": "YOUR_SIGNATURE",
"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"
}
}
Cargar el archivo en el almacenamiento temporal
POST {data.upload_host}
Reemplace
{data.upload_host}con eldata.upload_hostde la respuesta de credencial.
Parámetros de solicitud
Location | Campo | Tipo | Obligatorio | Descripción | Ejemplo |
|---|---|---|---|---|---|
Header | Content-Type | _string_ | No | Envíe el formulario como |
|
form-data | OSSAccessKeyId | _text_ | Sí |
|
|
form-data | política | _text_ | Sí |
|
|
form-data | Signature | _text_ | Sí |
|
|
form-data | key | _text_ | Sí |
|
|
form-data | x-oss-object-acl | _text_ | Sí |
|
|
form-data | x-oss-forbid-overwrite | _text_ | Sí |
|
|
form-data | success_action_status | _text_ | No | Código de estado HTTP devuelto en caso de éxito. Normalmente |
|
form-data | file | _file_ | Sí | El archivo a cargar. Solo se permite un archivo por solicitud. El campo |
|
En caso de éxito, la API devuelve HTTP 200 sin cuerpo de respuesta.
Solicitud de ejemplo
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"'
Construya la URL del archivo
Concatene oss:// con la key de la solicitud de carga. Esta URL es válida durante 48 horas.
oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.png
Códigos de error
Si las llamadas a la API fallan, consulte Mensajes de error para la resolución general de problemas.
Estos códigos de error son específicos de las cargas de archivos temporales:
Estado HTTP | Código de error | Mensaje de error | Causa y solución |
|---|---|---|---|
400 | invalid_parameter_error | InternalError.Algo.InvalidParameter: La URL proporcionada no parece ser válida. Asegúrese de que tenga el formato correcto. | La URL tiene un formato incorrecto. Verifique el formato de la URL. Si utiliza una URL |
400 | InvalidParameter.DataInspection | El formato multimedia no es compatible o es incorrecto para la inspección de datos. | Falta el encabezado de solicitud |
403 | AccessDenied | Inválido según la política: La política ha caducado. | La credencial de carga ha caducado. Llame nuevamente a la API de credenciales para obtener una nueva. |
429 | Throttling.RateQuota | Se ha excedido el límite de tasa de solicitudes; inténtelo de nuevo más tarde. | La tasa de solicitudes supera los 100 QPS. Reduzca la frecuencia de solicitudes o migre a OSS para cargas de trabajo de producción. |
FAQ
¿Qué debo hacer si una URL oss:// devuelve un error?
Siga estos pasos:
- Verifique el encabezado de la solicitud. Si llama a la API mediante HTTP (curl, Postman, etc.), agregue
X-DashScope-OssResourceResolve: enableal encabezado de la solicitud. Sin este encabezado, el servidor no puede resolver el protocolooss://. El SDK de DashScope agrega este encabezado automáticamente. - Verifique la validez de la URL. La URL
oss://caduca 48 horas después de la carga. Si ha caducado, cargue el archivo nuevamente para obtener una nueva URL.
¿Puedo usar diferentes claves de API para la carga de archivos y las llamadas al modelo?
Sí, siempre que ambas claves de API pertenezcan a la misma cuenta de Alibaba Cloud. El acceso a los archivos se gestiona a nivel de cuenta, no a nivel de clave de API.
Las claves de API de diferentes cuentas de Alibaba Cloud no pueden acceder a los archivos cargados por otras cuentas.