如何从base64 Python发送多部分/表单文件

时间:2019-12-19 12:51:03

标签: python python-requests base64 multipartform-data

如何在Python中使用多部分表单数据发送base64图像?

我使用一个请求模块,并从文件中读取base64字符串

我需要以多部分形式发送图像,但是此文件已被base64解码。如何解决?

此代码不发送文件...:(

data = pd.DataFrame({'Names': ['Joe', 'John', 'Jasper', 'Jez'] *4, 
                     'Add': ['Lo', 'Po', 'Fa', 'It']*4,
                     'Ob1' : np.random.rand(16), 
                     'Ob2' : np.random.rand(16)})

c = [gr[1] for gr in data.groupby(['Names', 'Add'])]
print(c[3])

Names Add Ob1 Ob2
1 John Po 0.930007 0.994919
5 John Po 0.803813 0.946720
9 John Po 0.561481 0.620958
13 John Po 0.238159 0.863743

1 个答案:

答案 0 :(得分:1)

仅转储传递的数据的测试文件和测试url的工作示例。

import base64
from io import BytesIO
from pprint import pprint

import requests

iamge = open("template.txt", "r").read()
decoded_image = base64.b64decode(iamge)

files = {
    'file1': ('test file.csv', BytesIO(decoded_image))
}

r = requests.post("https://httpbin.org/post", files=files)
pprint(r.json())

print('++++++++++ Body debug ++++++++++')
print(r.request.body.decode())


输出

# > python test.py
{'args': {},
 'data': '',
 'files': {'file1': 'How to send base64 image using multipart form data in '
                    'Python?\n'
                    '\n'
                    'I use a requests module, and read base64 string from '
                    'file\n'
                    '\n'
                    'I need to send image by multipart form, but this file is '
                    'base64 decoded. How to solve it?\n'
                    '\n'
                    'This code does not send file... :('},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Content-Length': '397',
             'Content-Type': 'multipart/form-data; '
                             'boundary=ea195eaa1aa183b4b32cc5c125ee0b64',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.22.0'},
 'json': None,
 'origin': '188.85.244.205, 188.85.244.205',
 'url': 'https://httpbin.org/post'}
++++++++++ Body debug ++++++++++
--ea195eaa1aa183b4b32cc5c125ee0b64
Content-Disposition: form-data; name="file1"; filename="test file.csv"

How to send base64 image using multipart form data in Python?

I use a requests module, and read base64 string from file

I need to send image by multipart form, but this file is base64 decoded. How to solve it?

This code does not send file... :(
--ea195eaa1aa183b4b32cc5c125ee0b64--

  

您不应传递headers = {'content-type': 'multipart/form-data'},因为文件上传还需要boundary=xxxxx才能将POST正文分割为命名序列。