Skip to main content

Upload local files to get temporary URLs

Multimodal models such as Qwen-VL require file URLs for image, video, and audio inputs. Model Studio provides free temporary storage if you lack public URLs: upload a file and get an oss:// URL valid for 48 hours .

Usage restrictions

  • File-model binding: You must specify the model name when uploading a file, and the model must be the same as the one used in subsequent calls. Files cannot be shared across different models.
  • File size limit: Files uploaded through this API must not exceed 1GB. Exceeding this limit causes the upload to fail. In addition, different models impose different limits on input file sizes. Exceeding these limits causes model calls to fail.
  • File-account binding: The API keys used for file upload and model calls must belong to the same Alibaba Cloud primary account. Uploaded files can only be used by that primary account and the corresponding model, and cannot be shared with other primary accounts or models.
  • File validity period: Files are valid for 48 hours after upload and are automatically cleaned up after they expire. Make sure you complete model calls within the validity period.
  • File usage restrictions: Once uploaded, files cannot be queried, modified, or downloaded. They can only be used as URL parameters in model calls.
  • Upload rate limit: The file upload credential API is rate-limited to 100 QPS per "Alibaba Cloud primary account + model". Exceeding the rate limit causes requests to fail.
  • Temporary URLs are valid for 48 hours and cannot be used after they expire. Do not use them in production environments.
  • The file upload credential API is rate-limited to 100 QPS and does not support scale-out. Do not use it in production environments, high-concurrency scenarios, or stress tests.
  • For production environments, we recommend using stable storage such as Alibaba Cloud OSS to ensure long-term file availability and avoid rate limit issues.
This feature is available in the China (Beijing) and Singapore regions. The code examples in this document use the Beijing region by default. To use the Singapore region, follow the comments in the examples to replace dashscope.aliyuncs.com with dashscope-intl.aliyuncs.com in the request URL, and use an API key for the Singapore region (the API keys of the two regions are different; see Get an API key).

How to use

  1. Get a file URL: First upload a file (image, video, or audio) in Step 1 to get a temporary URL prefixed with oss://.
  2. Call the model: Make sure to use the temporary URL for the call as described in Step 2. This step cannot be skipped; otherwise the API returns an error.

Step 1: Get a temporary URL

  • Method 1: Upload a file with code
  • Method 2: Upload a file with the CLI
This document provides Python and Java example code to simplify file uploads. You only need to specify the model and the file to upload to get a temporary URL.PrerequisitesBefore calling the API, you need to get an API key and then configure the API key as an environment variable.

Example code

  • Python
  • Java
  • DashScope SDK (Python)
  • dashscope CLI
Environment configuration
  • Python 3.9 or later is recommended.
  • Install the required dependencies.
pip install -U requests
Parameters
  • api_key: The Alibaba Cloud Model Studio API key.
  • model_name: The model that the file will be used with, such as qwen3-vl-plus.
  • file_path: The path of the local file to upload (image, video, etc.).
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 Beijing and Singapore regions are different. Use the key for the corresponding region.
    # The following is the Beijing region URL. For the Singapore region, replace the URL with: https://dashscope-intl.aliyuncs.com/api/v1/uploads
    url = "https://dashscope.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 temporary storage 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):
    """Upload the file and get the URL"""
    # 1. Get the upload credential. The credential API is rate-limited, and exceeding the rate limit causes requests to fail
    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

# Usage example
if __name__ == "__main__":
    # Get the API key from the environment variable, or set it in the code: api_key = "your_api_key"
    api_key = os.getenv("DASHSCOPE_API_KEY")
    if not api_key:
        raise Exception("Please set the DASHSCOPE_API_KEY environment variable")

    # Set the model name
    model_name="qwen3-vl-plus"

    # Path of the file to upload
    file_path = "/tmp/cat.png"  # Replace with the actual file path

    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. The URL is valid for 48 hours. 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 in the oss:// format, you must explicitly add the parameter X-DashScope-OssResourceResolve: enable to the HTTP request header (Header). For more information, see https://help.aliyun.com/en/model-studio/get-temporary-file-url#http")

    except Exception as e:
        print(f"Error: {str(e)}")
Example output
File uploaded successfully. The URL is 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 in the oss:// format, you must explicitly add the parameter X-DashScope-OssResourceResolve: enable to the HTTP request header (Header). For more information, see https://help.aliyun.com/en/model-studio/get-temporary-file-url#http
After you obtain the temporary URL, you must explicitly add the parameter X-DashScope-OssResourceResolve: enable to the HTTP request header (Header) when making a call. For more information, see Call via HTTP.

Step 2: Call the model with the temporary URL

Usage restrictions

  • File format: The temporary URL must be generated using the preceding methods and be a URL string prefixed with oss://.
  • File not expired: The file URL is still within the 48-hour validity period after upload.
  • Model consistency: The model used in the model call must be exactly the same as the model specified at upload.
  • Account consistency: The API key used in the model call and the API key used at upload must belong to the same Alibaba Cloud primary account.

Method 1: Call via HTTP

If you call the API directly with curl, Postman, or any other HTTP client, you must follow these rules:
  • When using a temporary URL, you must add the parameter X-DashScope-OssResourceResolve: enable to the request Header.
  • If this header is missing, the system cannot resolve the oss:// link and the request fails. For error messages, see Error codes.
  • Sample request
  • Sample response
  • Example of the uploaded local image
This example calls the qwen3-vl-plus model to recognize the content of an image.
Replace oss://... with your actual temporary URL; otherwise the request fails.
# The following is the Beijing region URL. For the Singapore region, replace the URL with: https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions
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": "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"}}]
    }]
}'

Method 2: Call with the DashScope SDK

You can also use the Python or Java SDK provided by Alibaba Cloud Model Studio.
  • Pass the URL directly: When calling the model SDK, pass the oss://-prefixed URL string directly as the file parameter.
  • No header configuration required: The SDK automatically adds the required request headers, so no extra action is needed.
Note: Not all models support SDK calls. Refer to the model API documentation.
The OpenAI SDK is not supported.
  • Python
  • Java
PrerequisitesInstall the DashScope Python SDK with a version number >= 2.0.1.Example codeThis example calls the qwen3-vl-plus model to recognize the content of an image. This code example applies only to qwen-vl and omni series models.
  • Sample request
  • Sample response
Replace oss://... in the image parameter with your actual temporary URL; otherwise the request fails.
import os
import dashscope

# The API keys for the Beijing and Singapore regions are different. Use the key for the corresponding region.
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
client = dashscope.Client(api_key=os.getenv('DASHSCOPE_API_KEY'))

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?"}]
    }]

response = client.multimodal.chat.create(
    model='qwen3-vl-plus',
    messages=messages
)

print(response.output_text)

Additional API details

In the two methods of getting a temporary URL described above, the code calls and the CLI have integrated the following three steps to simplify file uploads. This section describes the API for each step.

Step 1: Get a file upload credential

Prerequisites
You need to get an API key and configure the API key as an environment variable.
Request endpoint
Beijing region: GET https://dashscope.aliyuncs.com/api/v1/uploads
Singapore region: GET https://dashscope-intl.aliyuncs.com/api/v1/uploads
The file upload credential API is rate-limited to 100 QPS (per "Alibaba Cloud primary account + model"), and the temporary storage cannot be scaled out. For production environments or high-concurrency scenarios, use storage services such as Alibaba Cloud OSS.
Request parameters

Location

Field

Type

Required

Description

Example value

Header

Content-Type

string

Yes

Request type: application/json.

application/json

Authorization

string

Yes

The Alibaba Cloud Model Studio API key, for example: Bearer sk-xxx.

Bearer sk-xxx

Params

action

string

Yes

The operation type. In this scenario, it is getPolicy.

getPolicy

model

string

Yes

The name of the model to call.

qwen3-vl-plus

Response parameters

Field

Type

Description

Example value

request_id

string

The unique system ID of this request.

7574ee8f-...-11c33ab46e51

data

object

-

-

data.policy

string

The upload credential.

eyJl...1ZSJ9XX0=

data.signature

string

The signature of the upload credential.

g5K...d40=

data.upload_dir

string

The directory for the uploaded file.

dashscope-instant/xxx/2024-07-18/xxxx

data.upload_host

string

The upload host address.

https://dashscope-file-xxx.oss-cn-beijing.aliyuncs.com

data.expire_in_seconds

string

The validity period of the credential (in seconds).

After the credential expires, call this API again to get a new credential.

300

data.max_file_size_mb

string

The maximum file size allowed for this upload (in MB). This value depends on the model to be accessed.

100

data.capacity_limit_mb

string

The daily upload capacity limit for the same primary account (in MB).

999999999

data.oss_access_key_id

string

The access key used for the upload.

LTAxxx

data.x_oss_object_acl

string

The access permission of the uploaded file. private means private.

private

data.x_oss_forbid_overwrite

string

Whether files with the same name can be overwritten. true means they cannot be overwritten.

true

Sample request
# The following is the Beijing region URL. For the Singapore region, replace the URL with: https://dashscope-intl.aliyuncs.com/api/v1/uploads
curl --location 'https://dashscope.aliyuncs.com/api/v1/uploads?action=getPolicy&model=qwen3-vl-plus' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json'
If the Alibaba Cloud Model Studio API key is not configured as an environment variable, replace $DASHSCOPE_API_KEY with your actual API key, for example: --header "Authorization: Bearer sk-xxx".

Sample response

{
    "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"
    }
}

Step 2: Upload the file to temporary storage

Prerequisites

  • You have obtained a file upload credential.
  • Make sure the file upload credential is within its validity period. If the credential expires, call the API in Step 1 again to get a new credential.
    To check the validity period of the file upload credential: the output parameter data.expire_in_seconds of Step 1 is the credential validity period, in seconds.

Request endpoint

POST {data.upload_host}
Replace {data.upload_host} with the value of the output parameter data.upload_host from Step 1.

Request parameters

LocationFieldTypeRequiredDescriptionExample value
HeaderContent-TypestringNoThe form must be submitted as multipart/form-data.When the form is submitted, Content-Type appears in the format multipart/form-data;boundary=xxxxxx.
The boundary is a randomly generated string and does not need to be specified manually. If an SDK is used to construct the form, the SDK also generates this random value automatically.
multipart/form-data; boundary=9431149156168
form-dataOSSAccessKeyIdtextYesThe value of the output parameter data.oss_access_key_id of the file upload credential API.LTAm5xxx
policytextYesThe value of the output parameter data.policy of the file upload credential API.g5K...d40=
SignaturetextYesThe value of the output parameter data.signature of the file upload credential API.YOUR_SIGNATURE
keytextYesThe value of the output parameter data.upload_dir of the file upload credential API, appended with / and the file name.For example, if upload_dir is dashscope-instant/xxx/2024-07-18/xxx and the file to upload is named cat.png, the complete concatenated path is:dashscope-instant/xxx/2024-07-18/xxx/cat.png
x-oss-object-acltextYesThe value of the output parameter data.x_oss_object_acl of the file upload credential API.private
x-oss-forbid-overwritetextYesThe value of the output parameter data.x_oss_forbid_overwrite of the file upload credential API.true
success_action_statustextNoTypically 200. After the upload is complete, the API returns HTTP code 200, indicating a successful operation.200
filetextYesThe file or text content.
  • Only one file can be uploaded at a time.
  • The file field must be the last form field. The order of the other form fields, except file, does not matter.
For example, if the file to upload cat.png is stored in the /tmp directory on a Linux system, this field should be file=@"/tmp/cat.png".

Response parameters

When the call succeeds, this API has no output parameters.

Sample request

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"'

Step 3: Generate the file URL

File URL concatenation logic: oss:// + key (the input parameter key of Step 2). The URL is valid for 48 hours.
oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.png

Error codes

If an API call fails and returns an error message, see Error codes for troubleshooting. This API also has specific status codes, as shown below.
HTTP status codeAPI error code (code)API error message (message)Description
400invalid_parameter_errorInternalError.Algo.InvalidParameter: The provided URL does not appear to be valid. Ensure it is correctly formatted.The URL is invalid. Check whether the URL is correct.
If you use a temporary file URL, make sure the parameter X-DashScope-OssResourceResolve: enable is added to the request Header.
400InvalidParameter.DataInspectionThe media format is not supported or incorrect for the data inspection.Possible causes:
  • The request Header is missing a required parameter. Set X-DashScope-OssResourceResolve: enable.
  • The uploaded image format does not meet the model requirements. For more information, see Error codes.
403AccessDeniedInvalid according to Policy: Policy expired.The file upload credential has expired.Call the file upload credential API again to generate a new credential.
429Throttling.RateQuotaRequests rate limit exceeded, please try again later.The call frequency has triggered rate limiting.The file upload credential API is rate-limited to 100 QPS (per Alibaba Cloud primary account + model). After rate limiting is triggered, we recommend reducing the request frequency, or migrating to your own storage service such as OSS to avoid the limit.

FAQ

Q: What should I do if an error occurs when I call with a URL prefixed with oss://?

A: Troubleshoot as follows:
  1. Check the request header (Header):
    If you call the API directly over HTTP (such as with Postman or curl), you must add the parameter X-DashScope-OssResourceResolve: enable to the Header. Without this parameter, the server cannot recognize the OSS internal protocol. For request header configuration, see Call via HTTP.
  2. Check URL validity:
    oss:// links are temporary URLs. Make sure the link was generated within the last 48 hours. If the link has expired, upload the file again to get a new URL.

Q: Can the API keys used for file upload and model calls be different?

A: File storage and access permissions are managed at the Alibaba Cloud primary account level. An API key is only an access credential for the primary account. Therefore, different API keys under the same Alibaba Cloud primary account can be used normally. API keys from different primary accounts are isolated by account, and model calls cannot read files across accounts. Make sure the API keys used for file upload and model calls belong to the same Alibaba Cloud primary account.