Home >Backend Development >Python Tutorial >How to Send Multipart/Form-Data with Files and Form Data Using Python's Requests Library?

How to Send Multipart/Form-Data with Files and Form Data Using Python's Requests Library?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 12:25:13399browse

How to Send Multipart/Form-Data with Files and Form Data Using Python's Requests Library?

Sending Multipart/Form-Data Using Requests in Python

Multipart/form-data is a request format that allows for both form data and files to be sent in a single request. To use this format with requests in Python, specify a files parameter, which should be a dictionary where the keys are form data parameter names and the values are either file paths or tuples containing file content.

The following example demonstrates sending a file along with a text form value:

import requests

files = {'file_field': 'path/to/file.ext', 'text_field': 'text_value'}

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

Controlling Filename and Content Type

You can control the filename and content type of each part by using a tuple as the value in the files dictionary. The tuple should contain 2 to 4 elements, as follows:

  • Element 1: filename (optional)
  • Element 2: content
  • Element 3 (optional): content type
  • Element 4 (optional): extra headers

For example, to specify a filename and content type for a text value:

files = {'text_field': (None, 'text_value', 'text/plain')}

Specifying Multiple Fields with the Same Name

To send multiple fields with the same name, use a list of tuples as the value in the files dictionary.

Using Requests-Toolbelt for Advanced Multipart Support

The requests-toolbelt project provides advanced Multipart support. Unlike requests, it defaults to not setting a filename parameter and allows fields to be streamed from open file objects.

Here's an example using requests-toolbelt:

from requests_toolbelt.multipart.encoder import MultipartEncoder

mp_encoder = MultipartEncoder(
    fields={
        'file_field': ('file.ext', open('path/to/file.ext', 'rb'), 'application/octet-stream'),
        'text_field': 'text_value',
    }
)

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

The above is the detailed content of How to Send Multipart/Form-Data with Files and Form Data Using 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