Python + request implements multipart/form-data request to upload files

1. Introduction to multipart/form-data

        multipart/form-data is a type used in the HTTP protocol for uploading files. It allows a client to send a file to the server along with some additional metadata (such as filename, MIME type, image, etc.). This type of request differs from the normal application/x-www-form-urlencoded format, where data is encoded in the request body.

2. Implementation method

Premise : You need to download the requests-toolbelt module, just search and download it directly in the pycharm module library, or use pip

import requests
from requests_toolbelt import MultipartEncoder

header = {}    # 请求头
file_path = r"E:\data\test.jpg"    # 文件绝对路径
with open(file=file_path, mode='rb') as fis:
    file_content = fis
    files = {
        'filename': file_path,
        'Content-Disposition': 'form-data;',
        'Content-Type': 'image/jpeg',
        'file': (file_path, file_content, 'image/jpeg')
    }
    form_data = MultipartEncoder(files)  # 格式转换
    header['content-type'] = form_data.content_type
    r = requests.post(url, data=form_data, headers=header)    # 请求

3. The file path and file name are uploaded separately (beautiful)

import os
import requests
from requests_toolbelt import MultipartEncoder

filename = test.jpg    # 文件名,文件放在data目录下
header = {}    # 请求头
BASE_PATH = os.path.dirname(__file__)    # 当前工作路径

file_path = BASE_PATH + os.sep + "data" + os.sep    # 文件绝对路径
with open(file=file_path + filename, mode='rb') as fis:
    file_content = fis
    files = {
        'filename': file_path + filename,
        'Content-Disposition': 'form-data;',
        'Content-Type': 'image/jpeg',
        'file': (filename, file_content, 'image/jpeg')
    }
    form_data = MultipartEncoder(files)  # 格式转换
    header['content-type'] = form_data.content_type
    r = requests.post(url, data=form_data, headers=header)    # 请求

Guess you like

Origin blog.csdn.net/ouihsiad/article/details/129840445