All Products
Search
Document Center

Alibaba Cloud Model Studio:Upload a local file to obtain a temporary URL

Last Updated:Oct 27, 2025

When you call multi-modal models, such as image, video, or audio models, you often need to provide a file URL. To facilitate this, Alibaba Cloud Model Studio provides free temporary storage space. You can upload local files to this space and obtain a URL that is valid for 48 hours.

Important

This document applies only to the China (Beijing) region. To use the models, you must use an API key from the China (Beijing) region.

Limitations

  • File-model binding: You must specify a model name when you upload a file. This model must be the same model that you use in subsequent calls because different models cannot share files. Additionally, each model has a specific file size limit. If you exceed the limit, the upload fails.

  • File-account binding: The API keys used for the file upload and model calls must belong to the same Alibaba Cloud account. The uploaded file can only be used by that account and its corresponding model. It cannot be shared with other Alibaba Cloud accounts or models.

  • File validity period: After a file is uploaded, it is valid for 48 hours, after which it is automatically deleted. Ensure that you complete the model call within this validity period.

  • File usage limits: After a file is uploaded, it cannot be queried, modified, or downloaded. It can only be used as a URL parameter in model calls.

  • Upload rate limiting: The API for obtaining an upload credential is limited to 100 queries per second (QPS) for each Alibaba Cloud account and model. Requests that exceed this limit will fail.

Important
  • The temporary URL is valid for 48 hours and cannot be used after it expires. Do not use it in a production environment.

  • The API for obtaining an upload credential is limited to 100 QPS and does not support scaling out. Do not use it in production environments, high-concurrency scenarios, or stress testing scenarios.

  • For production environments, use a stable storage service such as Alibaba Cloud OSS to ensure long-term file availability and avoid rate limiting issues.

Procedure

  • Step 1: Upload a file, such as an image, video, or audio file, to obtain a temporary URL that is prefixed with oss://.

  • Step 2: Use the temporary URL to call the model.

    When you call a model using HTTP, such as with curl or Postman, you add X-DashScope-OssResourceResolve: enable to the request header. If you use the official DashScope SDK, you can skip this step. The SDK adds the header automatically.

Step 1: Obtain a temporary URL

Method 1: Upload a file using code

This topic provides Python and Java sample code to simplify file uploads. Simply specify the model and the file to upload to obtain a temporary URL.

Prerequisites

Before you make calls, you must obtain and configure an API key, and then set the API key as an environment variable.

Sample code

Python

Environment configuration

  • Python 3.8 or later is recommended.

  • Install the required dependency packages.

pip install -U requests

Input parameters

  • api_key: Your Model Studio API key.

  • model_name: The model that will use the file, such as qwen-vl-plus.

  • file_path: The path of the local file to upload, such as an image or video file.

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."""
    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 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. The API for getting an upload credential is subject to rate limiting. Requests that exceed the limit 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

# Example
if __name__ == "__main__":
    # Get the API key from an environment variable or set api_key = "your_api_key" in the code.
    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="qwen-vl-plus"

    # The 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. It is valid for 48 hours. Expiration time: {expire_time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"Temporary URL: {public_url}")
        print("When using this URL, see Step 2 in the documentation to avoid errors.")

    except Exception as e:
        print(f"Error: {str(e)}")

Sample output

File uploaded successfully. It 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
When using this URL, see Step 2 in the documentation to avoid errors.

Java

Environment configuration

  • JDK 1.8 or later is recommended.

  • Import the following dependencies into the pom.xml file of your Maven project.

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

Input parameters

  • apiKey: Your Model Studio API key.

  • modelName: The model that will use the file, such as qwen-vl-plus.

  • filePath: The path of the local file to upload, such as an image or video file.

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.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) {
        // Get 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 = "qwen-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. It is valid for 48 hours. Expiration time: " + expireTime.format(formatter));
            System.out.println("Temporary URL: " + publicUrl);
            System.out.println("When using this URL, see Step 2 in the documentation to avoid errors.");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Sample output

File uploaded successfully. It 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
When using this URL, see Step 2 in the documentation to avoid errors.

Method 2: Upload a file using the command line interface

For developers familiar with the command line, you can use the command line interface (CLI) provided by DashScope to upload files. After you run the command, you obtain a temporary URL.

Prerequisites

  1. Environment: Python 3.8 or later is recommended.

  2. API key: Before you begin, you must obtain and configure an API key.

  3. Install the SDK: The DashScope Python SDK version must be 1.24.0 or later. Run the following command to install or upgrade it:

pip install -U dashscope

Method 1: Use an environment variable (recommended)

This method is more secure because it prevents the API key from being exposed in plaintext in your command history or scripts.

Prerequisite: You must have set the API key as an environment variable.

Run the upload command:

dashscope oss.upload --model qwen-vl-plus --file cat.png

Sample output:

Start oss.upload: model=qwen-vl-plus, file=cat.png, api_key=None
Uploaded oss url: oss://dashscope-instant/xxxx/2025-08-01/xxxx/cat.png

Method 2: Specify the API key using a command-line parameter (for temporary use)

Run the upload command:

dashscope oss.upload --model qwen-vl-plus --file cat.png --api_key sk-xxxxxxx

Sample output:

Start oss.upload: model=qwen-vl-plus, file=cat.png, api_key=sk-xxxxxxx
Uploaded oss url: oss://dashscope-instant/xxx/2025-08-01/xxx/cat.png

Command-line parameter description

Parameter

Required

Description

Example

oss.upload

Yes

The DashScope subcommand used to perform file upload operations.

oss.upload

--model

Yes

Specifies which model the file will be used for.

qwen-vl-plus

--file

Yes

The path of the local file. It can be a relative or absolute path.

cat.png, /data/img.jpg

--api_key

No

The Model Studio API key. If you have configured the environment variable, you do not need to specify this parameter.

sk-xxxx

Step 2: Use the temporary URL for a model call

Limitations

  • File format: The temporary URL must be generated using the methods described above and must be a URL string prefixed with oss://.

  • File not expired: The file URL is valid for 48 hours after upload.

  • Model consistency: The model that you use for the call must be the same as the model that you specified when you uploaded the file.

  • Account consistency: The API key for the model call must belong to the same Alibaba Cloud account as the API key that you used to upload the file.

Prerequisites

Before you make a call, you must activate the model service and obtain an API key, and then set the API key as an environment variable.

Method 1: Call using HTTP

If you call the API directly using curl, Postman, or any other HTTP client, you must follow these rules:

Important
  • When you use a temporary URL, you must add the following parameter to the request header: X-DashScope-OssResourceResolve: enable.

  • If this header is missing, the system cannot parse the oss:// link, and the request fails. For more information about the error, see Error codes.

Sample request

This example shows how to call the qwen-vl-plus model to identify the content of an image.

Note

Replace oss://... with the actual temporary URL. Otherwise, the request fails.

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

Sample response

{
  "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 scene, which emphasizes the subject-the kitten running forward. This photographic technique is called shallow depth of field (or large aperture effect). It makes the kitten in the foreground sharp and clear, while the background is blurred to highlight the subject and create a dreamlike effect. Overall, this photo gives a relaxed and pleasant feeling and captures the animal's behavior at the moment very well.",
        "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"
}

Example of the uploaded local image

Method 2: Call using the DashScope SDK

You can also use the Python or Java SDK provided by Model Studio.

  • Pass the URL directly: When you call the model SDK, directly pass the URL string prefixed with oss:// as the file parameter.

  • No need to worry about the header: The SDK automatically adds the required request header. No additional operations are needed.

Note: Not all models support SDK calls. For more information, see the API reference for the specific model.

The OpenAI SDK is not supported.

Python

Prerequisites

You must install the DashScope Python SDK, and the version must be 1.24.0 or later.

Sample code

This example shows how to call the qwen-vl-plus model to identify the content of an image. This code sample applies only to the qwen-vl and omni series models.

Sample request

Note

Replace oss://... in the image parameter with your actual temporary URL. Otherwise, the request fails.

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

# If you have not configured the environment variable, replace the following line with your Model Studio API key: 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)

Sample 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

Prerequisites

Make sure that you install the DashScope Java SDK, and that the version is 2.21.0 or later.

Sample code

This example shows how to call the qwen-vl-plus model to identify the content of an image. This code sample applies only to the qwen-vl and omni series models.

Sample request

Note

Replace oss://... with your actual temporary URL. Otherwise, the request fails.

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

    // If you have not configured the environment variable, replace the following line with your Model Studio API key: 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 /*| IOException*/ e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }

}

Sample response

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

Appendix: API reference

The two methods for obtaining a temporary URL, using code or the command line interface, integrate the following three steps to simplify file uploads. The API reference for each step is provided below.

Step 1: Get a file upload credential

Prerequisites

You have obtained and configured an API key and set the API key as an environment variable.

API endpoint
GET https://dashscope.aliyuncs.com/api/v1/uploads
Important

The API for obtaining a file upload credential is rate-limited to 100 QPS per Alibaba Cloud account and model. The temporary storage cannot be scaled out. For production environments or high-concurrency scenarios, use storage services such as Alibaba Cloud OSS.

Request parameters

Parameter passing method

Field

Type

Required

Description

Example value

Header

Content-Type

string

Yes

The request type: application/json.

application/json

Authorization

string

Yes

Your Model Studio API key. Example: Bearer sk-xxx.

Bearer sk-xxx

Params

action

string

Yes

The operation type. In this scenario, the value is getPolicy.

getPolicy

model

string

Yes

The name of the model to call.

qwen-vl-plus

Response parameters

Field

Type

Description

Example value

request_id

string

The unique ID of the 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 folder for uploading files.

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

data.upload_host

string

The host address for the upload.

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

data.expire_in_seconds

string

The validity period of the credential in seconds.

Note

After the credential expires, you must call this API operation again to get a new one.

300

data.max_file_size_mb

string

The maximum size of the file that can be uploaded, in MB.

This value is related to the model to access.

100

data.capacity_limit_mb

string

The daily upload capacity limit for an Alibaba Cloud 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 permissions for the uploaded file. The value private indicates that the file is private.

private

data.x_oss_forbid_overwrite

string

Specifies whether to overwrite a file that has the same name. The value true indicates that the file cannot be overwritten.

true

Sample request
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'
Note

If you have not configured the Model Studio API key as an environment variable, replace $DASHSCOPE_API_KEY with your API key. For example, --header "Authorization: Bearer sk-xxx".

Sample response

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

Step 2: Upload the file to the temporary storage space

Prerequisites

  • You have obtained the file upload credential.

  • Make sure that the file upload credential has not expired. If the credential has expired, call the API in Step 1 again to obtain a new one.

    To check the validity period of the file upload credential, view the data.expire_in_seconds response parameter from Step 1. The value is in seconds.

API endpoint

POST {data.upload_host}
Note

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

Request parameters

Parameter passing method

Field

Type

Required

Description

Example value

Header

Content-Type

string

No

The form must be submitted as multipart/form-data.

When you submit the form, the Content-Type is displayed in the format of multipart/form-data;boundary=xxxxxx.

The boundary is a randomly generated string that you do not need to specify. If you use an SDK to construct the form, the SDK also automatically generates this random value.

multipart/form-data; boundary=9431149156168

form-data

OSSAccessKeyId

text

Yes

The value of the data.oss_access_key_id response parameter from the API for getting a file upload credential.

LTAm5xxx

policy

text

Yes

The value of the data.policy response parameter from the API for getting a file upload credential.

g5K...d40=

Signature

text

Yes

The value of the data.signature response parameter from the API for getting a file upload credential.

Sm/tv7DcZuTZftFVvt5yOoSETsc=

key

text

Yes

The value of the data.upload_dir response parameter from the API for getting a file upload credential, appended with /filename.

For example, if upload_dir is dashscope-instant/xxx/2024-07-18/xxx and the name of the file to upload is cat.png, the resulting full path is:

dashscope-instant/xxx/2024-07-18/xxx/cat.png

x-oss-object-acl

text

Yes

The value of the data.x_oss_object_acl response parameter from the API for getting a file upload credential.

private

x-oss-forbid-overwrite

text

Yes

The value of the data.x_oss_forbid_overwrite response parameter from the API for getting a file upload credential.

true

success_action_status

text

No

The value is typically 200. After the upload is complete, the API returns HTTP status code 200 to indicate that the operation is successful.

200

file

text

Yes

The file or text content.

Note
  • Only one file can be uploaded at a time.

  • The file must be the last form field. The other form fields have no specific order.

For example, if the file to upload, cat.png, is stored in the /tmp path in a Linux system, the value here should be file=@"/tmp/cat.png".

Response parameters

If the call is successful, this API returns no response 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

The file URL is created by concatenating oss:// and the key value (the key request parameter from Step 2). This URL is valid for 48 hours.

oss://dashscope-instant/xxx/2024-07-18/xxxx/cat.png

Error codes

If an API call fails and an error message is returned, see Error messages for troubleshooting.

This API also returns the following specific status codes.

HTTP status code

Error code

Error message

Description

400

invalid_parameter_error

InternalError.Algo.InvalidParameter: The provided URL does not appear to be valid. Ensure it is correctly formatted.

Invalid URL. Check whether the URL is correct.

If you use a temporary file URL, make sure that the request header includes the X-DashScope-OssResourceResolve: enable parameter.

400

InvalidParameter.DataInspection

The media format is not supported or incorrect for the data inspection.

Possible reasons include the following:

  • 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 messages.

403

AccessDenied

Invalid according to Policy: Policy expired.

The file upload credential has expired.

Call the file upload credential API again to generate a new credential.

429

Throttling.RateQuota

Requests 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 account and model. If throttling is triggered, reduce the request frequency or migrate to your own storage service, such as OSS, to avoid the limit.

FAQ

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

File storage and access permissions are managed based on your Alibaba Cloud account. The API key is only an access credential for the account.

Therefore, you can use different API keys that belong to the same Alibaba Cloud account. However, you cannot use API keys from different Alibaba Cloud accounts because model calls cannot read files across accounts due to account fencing.

Make sure that the API keys that you use for the file upload and model calls belong to the same Alibaba Cloud account.