You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python3的requests库发送含图片与文本的MultipartForm请求?

Converting Node.js Multipart POST to Python Requests

To replicate your Node.js multipart POST request in Python using the requests library, here's a straightforward, equivalent implementation:

Step 1: Import Required Libraries

Start by importing the necessary modules for HTTP requests and JSON serialization:

import requests
import json

Step 2: Define Variables and Helper Logic

Recreate your original variables and the RequestData function (adjust the function body to match your Node.js logic):

file_path = "xxx.jpeg"
text = "xxx"
api_url = "http://xxx"

def request_data(text_input):
    # Replace this with your actual RequestData implementation from Node.js
    return {"text_content": text_input}

Step 3: Prepare Multipart Form Data

Use a list of tuples to construct your multipart parts—this preserves the order of parts (matching your Node.js code) and supports custom content types:

# Add your authorization header (replace with real credentials/token)
headers = {
    "Authorization": "YourAuthTokenOrCredentialsHere"
}

# Safely handle the image file with a `with` block to avoid resource leaks
with open(file_path, "rb") as image_file:
    multipart_parts = [
        # Image part: matches Node.js's Content-Disposition and Content-Type
        ("file", (file_path, image_file, "image/jpeg")),
        # JSON payload part: custom content type, no filename needed
        ("payload", (None, json.dumps(request_data(text)), "application/specified-content-type-xxx"))
    ]
    
    # Send the POST request
    response = requests.post(api_url, files=multipart_parts, headers=headers)

Step 4: Process the Response

Handle the API response based on your needs:

# Check request success
print(f"Status Code: {response.status_code}")

# Parse JSON response if applicable
try:
    response_json = response.json()
    print("Response Data:", response_json)
except ValueError:
    print("Non-JSON Response:", response.text)

Key Details to Note:

  • Part Order: Using a list ensures the image is sent first, followed by the JSON payload—this matches your Node.js code and may be required by the API.
  • Custom Content Type: The JSON part uses None as the filename (since it's not a file) and explicitly sets your custom content type.
  • File Safety: The with statement automatically closes the image file after the request completes.
  • Authorization: Don't forget to replace the placeholder in the headers dictionary with your actual authorization token or credentials.

If your original Node.js code specified a different name for the JSON payload in Content-Disposition (it wasn't included in your snippet), replace "payload" in the second tuple with that name.

内容的提问来源于stack exchange,提问作者Maiko Ohkawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:05:44