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

API新手求助:如何使用Python发送multipart/form-data格式的POST请求以上传Excel文件?

How to Send a Multipart/Form-Data POST Request for Excel File Upload in Python

Hey there! Let's sort this out for you—since you're new to API file uploads, it's totally normal to mix up a few details. First off, the code you wrote won't work as intended, and here's why:

What's Wrong with Your Current Code

  • You manually set the Content-Type header to the Excel file's MIME type, but when uploading files via multipart/form-data, this header needs to include a unique boundary string that separates parts of the request. Requests handles this automatically—setting it manually breaks the request structure.
  • You're using the data parameter instead of files. The data parameter is for regular form fields, while file uploads require the files parameter to properly format the multipart payload.

Correct Implementation with Requests

Here's the right way to send your request, with explanations:

import requests

# Define your API URL and file path
api_url = "your_api_endpoint_here"
filepath = "path/to/your/file.xlsx"

# Construct the files dictionary
# The key 'file' matches the form field name specified (file = file.xlsx)
# The tuple format is (filename, file_object, content_type)
files = {
    "file": ("file.xlsx", open(filepath, "rb"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
}

# Send the POST request
try:
    response = requests.post(api_url, files=files)
    # Check if the request was successful
    response.raise_for_status()
    print("Upload successful! Response:", response.text)
except FileNotFoundError:
    print("Error: The specified file doesn't exist.")
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
finally:
    # Make sure to close the file handle
    if 'file' in files:
        files['file'][1].close()

Key Notes to Remember

  • Let Requests handle headers: You don't need to set the Content-Type: multipart/form-data header manually—requests generates it with the correct boundary when you use the files parameter.
  • File tuple details: The tuple in the files dict includes:
    1. The filename you want to send to the API (matches your filename="" requirement)
    2. The opened file in binary read mode (rb)
    3. The MIME type of the Excel file, which you specified correctly
  • Clean up file handles: Always close the file after the request to avoid resource leaks—using a finally block (or a with statement for opening the file) is a good practice.

Optional: Adding Extra Form Fields

If your API requires additional form data alongside the file, you can include it with the data parameter:

extra_data = {"key1": "value1", "key2": "value2"}
response = requests.post(api_url, files=files, data=extra_data)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 23:12:32