Home >Backend Development >Python Tutorial >How to Upload Multipart Form Data with Python's Requests Library?

How to Upload Multipart Form Data with Python's Requests Library?

Barbara Streisand
Barbara StreisandOriginal
2024-12-30 09:51:11675browse

How to Upload Multipart Form Data with Python's Requests Library?

Uploading Multipart Form Data with Requests in Python

In Python, requests can be used to send "multipart/form-data" requests, which are commonly employed for uploading files and submitting form data to a web server.

Sending a Single File

To send a file, use the "files" parameter. The value of "files" should be a dictionary with a file path as the key and an open file object or a tuple as the value. For example:

import requests

with open('myfile.txt', 'rb') as f:
    files = {'myfile': f}

response = requests.post('http://example.com/upload', files=files)

Sending Form Data along with Files

To send form data in addition to files, you can use both the "files" and "data" parameters. The "data" parameter should be a dictionary with the form data key-value pairs.

import requests

with open('myfile.txt', 'rb') as f:
    files = {'myfile': f}

data = {'name': 'John Doe'}

response = requests.post('http://example.com/upload', files=files, data=data)

Using the Requests-Toolbelt for Multipart Support

The requests-toolbelt library provides an advanced MultipartEncoder class that simplifies the process of constructing multipart requests. The fields can be defined in the same format as the "files" parameter.

from requests_toolbelt.multipart.encoder import MultipartEncoder

fields = {
    'foo': 'bar',
    'spam': ('spam.txt', open('spam.txt', 'rb'), 'text/plain'),
}

multipart_encoder = MultipartEncoder(fields=fields)

response = requests.post('http://example.com/upload', data=multipart_encoder, headers={'Content-Type': multipart_encoder.content_type})

The above is the detailed content of How to Upload Multipart Form Data with Python's Requests Library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn