Skip to main content

Upload a document

This topic describes the syntax and provides examples of the Tongyi data mining API for uploading documents.

1. Request an upload lease

Request syntax

POST /zhiwen-file/apply_upload_lease HTTP/1.1

Request parameters

Name

Type

Required

Description

Example

fileName

string

Yes

The name of the document.

Alibaba Cloud Model Studio.pdf

sizeBytes

number

Yes

The size of the document to upload, in bytes.

28123

md5

string

Yes

The MD5 hash of the document.

Response parameters

Name

Type

Description

code

int

The status code.

data

object

The response data.

-param

object

The HTTP request parameters for uploading the document.

-headers

object

The key-value pairs to include in the header for step 2 (uploading the document). Both the key and value are strings.

-x-bailian-extra

string

-Content-Type

string

-method

string

The HTTP method to call.

-url

string

The URL to request for step 2 (uploading the document).

-type

string

The upload method for the document.

-lease_id

string

The unique ID of the lease. This parameter is required for step 3 (submitting the document for parsing).

requestId

string

The request ID.

success

boolean

Success

message

string

The response message.

Example

Sample success response JSON format
{
  "code": 200,
  "data": {
    "param": {
      "headers": {
        "x-bailian-extra": "PkdiMDOidwEwMTE4KnY2MQ==",
        "Content-Type": "text/plain"
      },
      "method": "PUT",
      "url": "https://dashscope-file-datacenter-prod-01.oss-cn-beijing.aliyuncs.com/1880205101189661/10064170/zhiwen/3631bf9f24ea4ac7b362a135deee7fec.1753176187488.txt?Expires=1753182187&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE"
    },
    "type": "OSS.PreSignedUrl",
    "lease_id": "3631bf9f24ea4ac7b3dr5135deee7fec.1752176287488"
  },
  "requestId": "e1cdcfab-897d-9b7b-8c38-72aa39a13c87",
  "success": true,
  "message": "Success"
}

2. Upload the document to OSS

Use the data.param.url, data.param.method, x-bailian-extra, and Content-Type parameters from data.param.headers returned in the previous step (requesting an upload lease) to upload your local document to Object Storage Service (OSS). The following code provides an example.
# This sample code is for reference only. Do not use it directly in a production environment.
import requests

def upload_file(pre_signed_url, file_path):
    try:
        # Set the request header.
        headers = {
            "x-bailian-extra": "Replace this with the value of the x-bailian-extra field from data.param.headers returned by the request an upload lease API call in the previous step.",
            "Content-Type": "Replace this with the value of the Content-Type field from data.param.headers returned by the request an upload lease API call in the previous step."
        }

        # Read and upload the document.
        with open(file_path, 'rb') as file:
            # The request method for uploading the document must be the same as the value of the method field in data.param returned by the request an upload lease API call in the previous step.
            response = requests.put(pre_signed_url, data=file, headers=headers)

        # Check the response status code.
        if response.status_code == 200:
            print("File uploaded successfully.")
        else:
            print(f"Failed to upload the file. ResponseCode: {response.status_code}")

    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":

    pre_signed_url_or_http_url = "Replace this with the value of the url field in data.param returned by the request an upload lease API call in the previous step."

    # The document source is local. Upload the local document to OSS.
    file_path = "Replace this with the actual local path of the document you want to upload."
    upload_file(pre_signed_url_or_http_url, file_path)

3. Submit the document for parsing

Request syntax

POST /zhiwen-file/submit_parse_file HTTP/1.1

Request parameters

Name

Type

Required

Description

Example

leaseId

string

Yes

The unique ID of the lease. You can obtain this ID by requesting a lease.

3631bf9f24ea4ac7b3dr5135deee7fec.1752176287488

Response parameters

Name

Type

Description

code

int

The status code.

data

object

-fileSize

string

The document size.

-docId

string

docId

-name

string

The document name.

-pageSize

number

The number of pages.

-type

string

The document type.

-url

string

The document URL.

-fileId

string

The file ID. This ID is required for subsequent conversations.

requestId

string

The request ID.

success

boolean

Indicates whether the request was successful.

message

string

The response message.

Example

Sample success response JSON format
{
  "code": 200,
  "data": {
    "fileSize": "280931",
    "docId": "1397267735092973568",
    "name": "Alibaba Cloud Model Studio",
    "pageSize": 5,
    "type": "pdf",
    "url": "https://dashscope-file-datacenter-prod-01.oss-cn-beijing.aliyuncs.com/1880205101189661/10064170/zhiwen/3631bf9f24ea4ac7b362a135deee7fec.1753176187488.pdf?Expires=1753435388&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
    "fileId": "file_zhiwen_XXX"
  },
  "requestId": "e33ba5e9-fef6-96ae-b8b0-1b4a0c151e2b",
  "success": true,
  "message": "Success"
}

Call examples

import hashlib
import os
import requests
from http import HTTPStatus

'''
API name: Upload a document
API paths: https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/apply_upload_lease
        https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/submit_parse_file
Environment requirements: Python >= 3.7
'''

apply_lease_url = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/apply_upload_lease"
submit_file_url = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-file/submit_parse_file"
request_headers = {
    "Authorization": os.environ.get("DASHSCOPE_API_KEY"),  # If you have not configured the environment variable, replace this with your API-KEY.
    "Content-Type": "application/json"
}

file_path = "./test.txt"
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
with open(file_path, 'rb') as f:
    md5 = hashlib.md5()
    while True:
        data = f.read(4096)  # Read 4 KB of data at a time.
        if not data:
            break
        md5.update(data)
file_md5 = md5.hexdigest()

# 1. Request a lease.
response = requests.post(apply_lease_url,
                         json={
                             "fileName": file_name,
                             "sizeBytes": file_size,
                             "md5": file_md5
                         },
                         headers=request_headers)
lease_data = {}
if response.status_code == HTTPStatus.OK:
    print("1. Lease applied successfully.")
    print(response.json())
    lease_data = response.json()['data']
else:
    print(f'response={response.json()}')
    print(f'code={response.status_code}')

# 2. Upload the document.
upload_headers = {
    "X-bailian-extra": lease_data['param']['headers']['x-bailian-extra'],
    "Content-Type": lease_data['param']['headers']['Content-Type']
}
with open(file_path, 'rb') as file:
    # The request method for uploading the document must be the same as the value of the Method field in Data.Param returned by the ApplyFileUploadLease API call in the previous step.
    response = requests.put(lease_data['param']['url'], data=file, headers=upload_headers)
if response.status_code == HTTPStatus.OK:
    print("2. File uploaded successfully.")
else:
    print(f"Failed to upload the file. ResponseCode: {response.status_code}")

# 3. Submit for parsing.
response = requests.post(submit_file_url,
                         json={
                             'leaseId': lease_data['lease_id']
                         },

                         headers=request_headers)
if response.status_code == HTTPStatus.OK:
    print("3. File submit parse successfully.")
    print(response.json())
else:
    print(f'response={response.json()}')
    print(f'code={response.status_code}')

Error codes

For more information, see Error codes for Tongyi data mining.
Agent Development
Agent Context
Agent Governance & Evolution
Store
Application Marketplace