Skip to content

How to upload local files to temporary storage space and get file URLs

Reference, synced 2026-06-13.

flowchart TD
  n0["Models"]
  n1["Overview"]
  n2["Products"]
  n3["Solutions"]
  n4["Pricing"]
  n5["Resources"]
  n6["Partners"]
  n7["Support"]
  n8["Language"]
  n0 --> n1
  n1 --> n2
  n2 --> n3
  n3 --> n4
  n4 --> n5
  n5 --> n6
  n6 --> n7
  n7 --> n8

Free access Accelerate Delivery with Fixed-Cost Agentic CodingWatch how it works

Models

Empowering AI innovation for both enterprises and developers with Alibaba Cloud’s best-in-class Qwen models, AI-native apps, and AI solutions.

Alibaba Cloud Model Studio \ Enterprise-grade large model service and application development platform.

Try Visual Model \ Supports image understanding, image generation, and video generation.

Models

HappyHorse-1.0-T2V \ Cinematic creative generation, ultimate dynamic details Qwen3-VL-Plus \ Native VL, spatial reasoning, 1M-context video analysis Wan2.7-VideoEdit \ Supports both localized and global editing with prompt

Qwen3.6-Plus \ Native multimodal, 1M context, agentic coding Wan2.7-Image-Pro \ Interactive editing, long-text rendering, precise prompt following Qwen-Plus \ Balanced intelligence, efficient inference, production-ready performance

Qwen-Image-2.0 \ Professional infographics, exquisite photorealism Z-Image-Turbo \ Ultra-fast image generation, high throughput, cost-optimized inference Qwen3-Coder-Next \ Multi-turn tool interactions, future-ready development support

Wan2.7-T2V \ High-fidelity T2V, 15s duration, advanced camera control Wan2.7-I2V \ Cinematic I2V with emotional depth and visceral impact Wan2.7-R2V \ Up to 5 mixed image/video inputs and audio timbre cloning

GenAI Application

Qoder \ Intelligent coding assistant, available for enterprise-dedicated deployment. Qoder CN \ AI-powered coding assistant that boosts developer productivity with intelligent code completion, AI chat, multi-file editing, and task automation.

AI Service

Model Experience \ Experience full-scale, multimodal model capabilities online. Platform for AI \ An AI-native algorithm engineering platform for end-to-end modeling, training, and inference service deployment. Fine-tune Video Generation Model \ Customize Wan’s text-to-video capabilities through model fine-tuning to meet your unique requirements.

AI Use Case

AI Savings Plan Hot \ Save up to 47% on AI costs. Limited-time offer tailored to your usage. AI Video Creation \ Elevate your professional video production with Wan 2.6.

AI Token Plan \ One plan. Multiple models. Big Savings with a Fixed Subscription. AI Image Creation \ All-in-one creative suite for copywriting, image generation, and poster design.

Overview

As a global full-stack AI leader, Alibaba Cloud aims to make computing accessible to everyone and help worldwide customers accelerate innovation.

Why Alibaba Cloud

About Alibaba Cloud \ AI Powered Cloud Technology Our Global Network \ Explore our global presence and deployment regions around the world Our Global Offices \ With offices in 4 continents, we're always close to where it matters.

Asia Accelerator \ Accelerate Success in Asia with Alibaba Cloud Go Global \ Benefits of our Global Alliance Trust Center \ Empowering enterprises with a secure, compliant, and globally trusted cloud infrastructure

Customers and Insights

Olympic Games \ Alibaba Cloud Powers Olympic Games with AI-powered cloud technology Case Studies \ Learn how customers are scaling their businesses on Alibaba Cloud Analyst Reports \ Learn what the top industry analyst firms are saying about Alibaba Cloud

What's New

Events and Webinars \ Quick access to upcoming and on-demand events Product Updates \ Stay informed of the latest innovations Press Room \ Latest news and media releases

Products

Featured ProductsAI & Machine Learning Computing Container Storage Networking & CDN Security Middleware Database Analytics ComputingMedia ServicesEnterprise Services & Cloud CommunicationDomain Names and WebsitesEnd User ComputingServerlessDeveloper ToolsMigration & O&M ManagementApsara Stack

Alibaba Cloud Model Studio \ Supercharge your AI journey effortlessly with industry-leading GenAI models ApsaraDB RDS \ Store and manage your business data, with automated monitoring and backups Certificate Management Service (Original SSL Certificate) \ Create a safe and secure connection between your website and users

Elastic Compute Service (ECS) \ Host websites anywhere and scale enterprise workloads Container Service for Kubernetes (ACK) \ Run and scale containerized applications on managed Kubernetes infrastructure Object Storage Service (OSS) \ Store large amounts of data in the cloud and access it anywhere, anytime

Simple Application Server (SAS) \ All-in-one services for fast deployment Elastic IP Address (EIP) \ Manage your public IPs independently to improve internet network quality Domain Names and Website \ Get the perfect domain name to suit your every need

Solutions

Solutions by Industry Technical Solutions AI WebsitesNetworking Security and ComplianceData and AnalyticsEnterprise Service and ApplicationCloud MigrationCloud NativeHybrid CloudSMB solutions

Financial Services \ Innovate faster with Alibaba Cloud Games \ Grow your game rapidly with high global availability

New Retail \ Alibaba Cloud enables digital retail transformation to fuel growth and realize an omnichannel customer experience throughout the consumer journey. Media and Entertainment \ Ready your content for today's media market with a digitalized media journey

Supply Chain \ Power your supply chain with intelligent, efficient, and reliable solutions Sports \ Digitizing the sports industry with intelligent tech

Sustainability \ Achieve a sustainable future with low-carbon and energy-efficient technologies

Pricing

Flexible options like pay-as-you-go and clear billing rules to meet diverse business needs.

Overview & Tools

Pricing Calculator \ Get an instant pricing estimate based on your usage and needs Free Trial \ Try our 80+ cloud products for free.

Pricing Options \ Get the most out of Alibaba Cloud with flexible pricing

Optimize your cost

Migrate & Save \ Superior Performance At Lower Pricing. Save up to 50%. Promotion Center \ Unlock the latest Alibaba Cloud offers & promos

Resources

Official documentation, extensive tools, training resources, and a community to grow and innovate in the cloud.

Technical Resources

Documentation \ Product guides and FAQs Architecture Center \ Design reliable, secure, and efficient cloud architecture. Intelligent Solution Explorer \ Find the right solution for you, powered by AI

Blog \ Latest cloud insights and developer trends Whitepapers \ Research that explores the how and why behind our technology

Training&Certification

Alibaba Cloud Academy \ Build cloud skills and earn certifications with expert-led training.

Developer Hub

Alibaba Cloud Project Hub \ Explore real-world projects built by developers using our platform. Our Developer MVPs \ Celebrating the developers who lead, build, and inspire our community

Partners

Partner-first strategy offering collaborative product, sales, and service models, plus high-quality partner solutions that complement Alibaba Cloud’s capabilities.

Marketplace

AI Alliance for ISVs \ Partner with us to build and grow AI solutions together ISV Benefits \ Unlock resources, market access, and go-to-market support as an ISV partner

Alibaba Cloud Marketplace \ Explore ready-to-deploy solutions from our partners and ISVs

Find a Partner

Partner Hub \ Find your ideal partner in no time

Become a Partner

Partner Network \ A partner portal for Alibaba Cloud Channel, Technology, MSP partner and other partner programs

Support

Full-lifecycle support and expert services, from cloud advisory and migration to operations.

Support & Professional Services

Professional Services \ Expert-led services to design, migrate, and optimize your cloud journey Support Plans \ Flexible support for every stage — from startup to enterprise

Partner Support Program \ Priority technical support for partners, with dedicated managers and faster issue resolution

Contact us

Connect With Us \

Talk to a sales expert and get a custom quote for your business

Language

  • English
  • 简体中文
  • 繁體中文
  • 日本語
  • Bahasa Indonesia

Locale

Visit aliyun.com

Documentation

Alibaba Cloud Model Studio

User Guide (Models) User Guide (Application) API Reference (Models) API Reference (Application)

Search for Help Content

Getting Started

The Beginner's Guide

Well-Architected Framework

AI & Machine Learning

Platform For AI

Alibaba Cloud Model Studio

DashVector

Artificial Intelligence Recommendation

OpenSearch

Image Search

Machine Translation

Intelligent Speech Interaction

Optimization Solver

Intelligent Computing LINGJUN

Computing

Elastic Compute Service

Elastic GPU Service

Elastic Container Instance

Dedicated Host

Compute Nest

Simple Application Server

Cloud Box

Auto Scaling

Elastic High Performance Computing

Batch Compute (Deprecated)

Function Compute

Serverless App Engine

ENS

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

Edge Network Acceleration

Alibaba Cloud Linux

AgentBay

Container

Container Service for Kubernetes

Container Compute Service

Container Registry

Storage

Object Storage Service

Cloud Parallel File Storage

File Storage NAS

Tablestore

Storage Capacity Unit

Simple Log Service

Cloud Backup

Intelligent Media Management

Drive and Photo Service

Data Transport

Cloud Storage Gateway

Data Online Migration

Hybrid Cloud Storage Array

Storage Services Overview

Backup and Disaster Recovery Center

Networking and CDN

Server Load Balancer

Elastic IP Address

Internet Shared Bandwidth

Data Transfer Plan

Virtual Private Cloud

NAT Gateway

PrivateLink

Alibaba Cloud DNS PrivateZone

Network Intelligence Service

Cloud Data Transfer

IPv6 Gateway

Anycast Elastic IP Address

Cloud Enterprise Network

Global Accelerator

VPN Gateway

Smart Access Gateway

Express Connect

CDN

Edge Security Acceleration

Cloud Network Well-architected Design Guidelines

Security

Anti-DDoS

Web Application Firewall

Cloud Firewall

Security Center

Bastionhost

Secure Access Service Edge

Certificate Management Service

Key Management Service

Data Security Center

Identity as a Service

Fraud Detection

AI Guardrails

Captcha

Blockchain as a Service

ID Verification

Managed Security Service

Middleware

Enterprise Distributed Application Service

Microservices Engine

Alibaba Cloud Service Mesh

SchedulerX

ApsaraMQ for RocketMQ

ApsaraMQ for Kafka

ApsaraMQ for RabbitMQ

ApsaraMQ for MQTT

Simple Message Queue (formerly MNS)

CloudFlow

EventBridge

Application Real-Time Monitoring Service

Managed Service for Prometheus

Managed Service for Grafana

Managed Service for OpenTelemetry

Performance Testing

STAROps

Databases

ApsaraDB Console

PolarDB

ApsaraDB RDS

ApsaraDB for OceanBase (Deprecated)

Tair (Redis® OSS-Compatible)

Lindorm

Time Series Database

ApsaraDB for MongoDB

ApsaraDB for HBase

ApsaraDB for Memcache

ApsaraDB for MyBase

AnalyticDB

ApsaraDB for ClickHouse

ApsaraDB for SelectDB

Data Transmission Service

Database Autonomy Service

Data Management

Database Gateway - Deprecated

ApsaraDB for Cassandra - Deprecated

Analytics Computing

MaxCompute

Hologres

Realtime Compute for Apache Flink

Elasticsearch

Vector Retrieval Service for Milvus

E-MapReduce

Data Lake Formation

DataV

Quick BI

Quick Audience

Quick Tracking

DataWorks

DataHub

Dataphin

Media Services

ApsaraVideo VOD

ApsaraVideo Live

Intelligent Media Services

ApsaraVideo Media Processing

Apsara Video SDK

Enterprise Services & Cloud Communication

Energy Expert

CloudQuotation

Salesforce on Alibaba Cloud

GoChina ICP Filing Assistant

Marketplace

Alibaba Mail

Direct Mail

Short Message Service

Voice Service

Phone Number Verification Service

Cell Phone Number Service

Chat App Message Service

Financial Intelligence Engine

Domain Names and Websites

Domain Names

ICP Filing

Alibaba Cloud DNS

End User Computing

Elastic Desktop Service

App Streaming

WUYING Terminal

Cloud Phone

AgentBay

Internet of Things

IoT Platform

Serverless

Serverless App Engine

CloudFlow

EventBridge

Simple Message Queue (formerly MNS)

Function Compute

Developer Tools

OpenAPI Explorer

Alibaba Cloud SDK

Cloud Shell

Resource Orchestration Service

Alibaba Cloud CLI

BSS OpenAPI

Terraform

Pulumi

Ticket System API

Mobile Platform as a Service

Alibaba Cloud DevOps

API Gateway

Cloud Control API

AI Coding Assistant Lingma

Cloud Skills Portal

Migration & O&M Management

CloudOps Orchestration Service

Cloud Monitor

Intelligent Advisor

Cloud Governance Center

ActionTrail

Cloud Config

Resource Access Management

Resource Management

Cloud Architect Design Tools

Migration Hub

Server Migration Center

Service Catalog

Logic Composer

Quota Center

CloudSSO

HTTPDNS

Solutions

SAP

SuperApp

OpenLake

Membership Service

Expenses and Costs

Account Center

More

Support

Legal

Tech Share Terms and Conditions

After Sales Support

China Gateway Program

Service Level Objectives

Management Console

Security Control

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.

Important

Temporary URLs are for development and testing only -- not for production, high-concurrency scenarios, or stress tests. For production workloads, use Object Storage Service (OSS) for long-term availability and to avoid rate limits.

Important

This feature is available only in the China (Beijing) region. Use an API key from this region.

How it works

  1. Upload a file and specify the target model. The API returns an oss:// URL.

  2. Pass that URL in your model call. You must complete Step 2 to use the temporary URL -- skipping it causes errors. For HTTP calls, add the header X-DashScope-OssResourceResolve: enable. The DashScope SDK adds this header automatically.

Limitations

ConstraintDetail
ConstraintDetail
File-model bindingSpecify the model name at upload. Use the same model in subsequent calls -- files cannot be shared across models. Each model enforces its own file size limit.
File-account bindingAPI keys for upload and model calls must belong to the same Alibaba Cloud account -- files cannot be shared across accounts.
48-hour expiryFiles are automatically deleted after 48 hours. Complete model calls within this period.
No post-upload managementFiles cannot be queried, modified, or downloaded -- they serve only as URL parameters in model calls.
Rate limitingThe upload credential API is limited to 100 QPS per account per model. Excess requests fail. The temporary storage does not support scale-out.

Prerequisites

Before you begin:

  • An API key configured as an environment variable

  • The model name that will consume the file (e.g., qwen-vl-plus)

Step 1: Get a temporary URL

Upload a file and get its temporary URL using one of these methods:

Upload with code

Upload with the CLI

Python

Java

Prerequisites

  • Python 3.8 or later

  • Install dependencies:

bash
pip install -U requests

Parameters

ParameterDescriptionExample
api_keyModel Studio API keyRead from DASHSCOPE_API_KEY environment variable
model_nameThe model that will consume the fileqwen-vl-plus
file_pathPath to the local file/tmp/cat.png

Example code

python
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-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="qwen-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/en/model-studio/get-temporary-file-url#http-call")

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

Example output

File 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/en/model-studio/get-temporary-file-url#http-call

Important

After obtaining the temporary URL, add the X-DashScope-OssResourceResolve: enable header to HTTP requests when making a call. For more information, see Call using HTTP.

Prerequisites

  • JDK 1.8 or later

  • Add the following dependencies to pom.xml:

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>

Parameters

ParameterDescriptionExample
apiKeyModel Studio API keyRead from DASHSCOPE_API_KEY environment variable
modelNameThe model that will consume the fileqwen-vl-plus
filePathPath to the local filesrc/main/resources/tmp/cat.png

Example code

java
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) {
        // 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 = "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. 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/en/model-studio/get-temporary-file-url#http-call");
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Example output

File 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/en/model-studio/get-temporary-file-url#http-call

Important

After obtaining the temporary URL, add the X-DashScope-OssResourceResolve: enable header to HTTP requests when making a call. For more information, see Call using HTTP.

The DashScope CLI uploads a file with a single command and returns the temporary URL.

Prerequisites

  • Python 3.8 or later

  • DashScope Python SDK version 1.24.0 or later:

bash
pip install -U dashscope

CLI parameters

ParameterRequiredDescriptionExample
oss.uploadYesDashScope subcommand for file uploadoss.upload
--modelYesTarget model for the fileqwen-vl-plus
--fileYesLocal file path (relative or absolute)cat.png, /data/img.jpg
--api_keyNoAPI key. Not required if the DASHSCOPE_API_KEY environment variable is set.sk-xxxx

Upload with the environment variable (recommended)

Prerequisite: Configure the API key as an environment variable:

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

Sample output:

plaintext
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

Upload with an inline API key

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

Sample output:

plaintext
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

Important

After obtaining the temporary URL, add the X-DashScope-OssResourceResolve: enable header to HTTP requests when making a call. For more information, see Call using HTTP.

Step 2: Call the model with the temporary URL

After uploading a file, use the oss:// URL in your model call. Two rules apply:

  • Model consistency: Use the same model you specified during upload.

  • Account consistency: Use an API key that belongs to the same Alibaba Cloud account.

Choose one of these methods:

HTTP

When calling the API over HTTP (curl, Postman, etc.), add this header:

X-DashScope-OssResourceResolve: enable

Without this header, the API cannot resolve oss:// URLs and requests fail.

Example request

This example calls qwen-vl-plus to describe an uploaded image.

Replace oss://... with your actual temporary URL.

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

Example response

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

The DashScope SDK handles the X-DashScope-OssResourceResolve header automatically -- pass the oss:// URL directly as the file parameter.

The OpenAI SDK is not supported. Not all models support SDK calls -- see the specific model's API reference for details.

Python

Java

Prerequisite: DashScope Python SDK1.24.0 or later.

This example calls qwen-vl-plus to describe an uploaded image. This code applies to qwen-vl and omni models.

Replace oss://... in the image parameter with your actual temporary URL.

python
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 not configured as environment variable, replace with: 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)

Example response

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

Prerequisite: DashScope Java SDK2.21.0 or later.

This example calls qwen-vl-plus to describe an uploaded image. This code applies to qwen-vl and omni models.

Replace oss://... with your actual temporary URL.

java
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 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 {
        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);
    }

}

Example response

json
{
    "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 reference

The code samples and CLI in Step 1 wrap these three API operations internally. Use this reference to implement the upload flow manually.

Get a file upload credential

http
GET https://dashscope.aliyuncs.com/api/v1/uploads

Important

The credential API is rate-limited to 100 QPS per account per model. The temporary storage cannot be scaled out. For production or high-concurrency workloads, use Alibaba Cloud OSS.

Request parameters

LocationFieldTypeRequiredDescriptionExample
LocationFieldTypeRequiredDescriptionExample
HeaderContent-Type_string_YesRequest type.application/json
HeaderAuthorization_string_YesModel Studio API key.Bearer sk-xxx
Paramsaction_string_YesOperation type. Set to getPolicy.getPolicy
Paramsmodel_string_YesTarget model name.qwen-vl-plus

Response parameters

FieldTypeDescriptionExample
FieldTypeDescriptionExample
request_id_string_Unique request ID.7574ee8f-...-11c33ab46e51
data_object_--
data.policy_string_Upload credential.eyJl...1ZSJ9XX0=
data.signature_string_Credential signature.g5K...d40=
data.upload_dir_string_Upload directory path.dashscope-instant/xxx/2024-07-18/xxxx
data.upload_host_string_OSS host for uploading.https://dashscope-file-xxx.oss-cn-beijing.aliyuncs.com
data.expire_in_seconds_string_Credential validity in seconds. Get a new credential after expiry.300
data.max_file_size_mb_string_Maximum upload file size in MB. Varies by model.100
data.capacity_limit_mb_string_Daily upload capacity per Alibaba Cloud account in MB.999999999
data.oss_access_key_id_string_Access key for the upload.LTAxxx
data.x_oss_object_acl_string_Uploaded file access permission. private means the file is private.private
data.x_oss_forbid_overwrite_string_Whether overwriting files with the same name is blocked. true means overwriting is blocked.true

Sample request

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

If the API key is not configured as an environment variable, replace $DASHSCOPE_API_KEY with your API key: --header "Authorization: Bearer sk-xxx".

Sample response

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

Upload the file to temporary storage

http
POST {data.upload_host}

Replace {data.upload_host} with the data.upload_host from the credential response.

Request parameters

LocationFieldTypeRequiredDescriptionExample
LocationFieldTypeRequiredDescriptionExample
HeaderContent-Type_string_NoSubmit the form as multipart/form-data. The boundary is automatically generated by your HTTP client.multipart/form-data; boundary=9431149156168
form-dataOSSAccessKeyId_text_Yesdata.oss_access_key_id from the credential response.LTAm5xxx
form-datapolicy_text_Yesdata.policy from the credential response.g5K...d40=
form-dataSignature_text_Yesdata.signature from the credential response.Sm/tv7DcZuTZftFVvt5yOoSETsc=
form-datakey_text_Yesdata.upload_dir from the credential response, appended with /<filename>.dashscope-instant/xxx/2024-07-18/xxx/cat.png
form-datax-oss-object-acl_text_Yesdata.x_oss_object_acl from the credential response.private
form-datax-oss-forbid-overwrite_text_Yesdata.x_oss_forbid_overwrite from the credential response.true
form-datasuccess_action_status_text_NoHTTP status code returned on success. Typically 200.200
form-datafile_file_YesThe file to upload. Only one file per request. The file field must be the last form field.file=@"/tmp/cat.png"

On success, the API returns HTTP 200 with no response body.

Sample request

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

Construct the file URL

Concatenate oss:// with the key from the upload request. This URL is valid for 48 hours.

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

Error codes

If API calls fail, see Error messages for general troubleshooting.

These error codes are specific to temporary file uploads:

HTTP statusError codeError messageCause and resolution
HTTP statusError codeError messageCause and resolution
400invalid_parameter_errorInternalError.Algo.InvalidParameter: The provided URL does not appear to be valid. Ensure it is correctly formatted.The URL is malformed. Verify the URL format. If using an oss:// URL over HTTP, add the X-DashScope-OssResourceResolve: enable header.
400InvalidParameter.DataInspectionThe media format is not supported or incorrect for the data inspection.The request header is missing X-DashScope-OssResourceResolve: enable, or the file format is not supported by the model. See Error messages.
403AccessDeniedInvalid according to Policy: Policy expired.The upload credential has expired. Call the credential API again to get a new one.
429Throttling.RateQuotaRequests rate limit exceeded, please try again later.The request rate exceeds 100 QPS. Reduce the request frequency, or migrate to OSS for production workloads.

FAQ

What should I do if an oss:// URL returns an error?

Follow these steps:

  1. Check the request header. If calling the API over HTTP (curl, Postman, etc.), add X-DashScope-OssResourceResolve: enable to the request header. Without this header, the server cannot resolve the oss:// protocol. The DashScope SDK adds this header automatically.

  2. Check URL validity. The oss:// URL expires 48 hours after upload. If expired, upload the file again to get a new URL.

Can I use different API keys for file upload and model calls?

Yes, as long as both API keys belong to the same Alibaba Cloud account. File access is managed at the account level, not the API key level.

API keys from different Alibaba Cloud accounts cannot access each other's uploaded files.

Previous: Model calls in a sub-workspaceNext: Configure connection reuse for DashScope SDK

Is this page helpful?

How it works

Limitations

Prerequisites

Step 1: Get a temporary URL

Step 2: Call the model with the temporary URL

HTTP

DashScope SDK

API reference

Get a file upload credential

Upload the file to temporary storage

Construct the file URL

Error codes

FAQ

What should I do if an oss:// URL returns an error?

Can I use different API keys for file upload and model calls?

Contact Us

Sales Support

Live-chat with our sales team or get in touch with a business development professional in your region.

Contact Sales

Technical Support

Open a ticket and get quick help from our technical team.

Open a Ticket >

Connect & Report Abuse

We look forward to your suggestion.

Post a Suggestion > Report Abuse >

Chat now with Alibaba Cloud Customer Service to assist you in finding the right products and services to meet your needs.

\ \ Hi, I'm Alibaba Cloud AI Assistant!\ \ I can help with questions and solutions.

Why Alibaba Cloud

About Alibaba Cloud

Asia Accelerator

Our Global Network

Global Offices

Trust Center

Case Studies

Analyst Reports

Products & Pricings

Pricing Calculator

ECS

SAS

Model Studio

Database

Security

SMS

Solutions

Financial Services

Retail Services

Media Services

Gaming Services

ISV Solutions

Engage

Developer Community

Partner Network

Startups

Marketplace

Join Alibaba Cloud

Resources & Support

Developer Learning Hub

Documentation Center

Training & Certification

Service Notices

Submit a Ticket

Security Report

Qwen Cloud

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

© 2009-2026 Copyright by Alibaba Cloud All rights reserved

Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links