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-Typeheader to the Excel file's MIME type, but when uploading files viamultipart/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
dataparameter instead offiles. Thedataparameter is for regular form fields, while file uploads require thefilesparameter 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-dataheader manually—requests generates it with the correct boundary when you use thefilesparameter. - File tuple details: The tuple in the
filesdict includes:- The filename you want to send to the API (matches your
filename=""requirement) - The opened file in binary read mode (
rb) - The MIME type of the Excel file, which you specified correctly
- The filename you want to send to the API (matches your
- Clean up file handles: Always close the file after the request to avoid resource leaks—using a
finallyblock (or awithstatement 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
相关产品推荐
相关产品推荐

