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



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

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

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

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

# base64 file /9j/4AAQSkZJRgABA...
ref_path = open("template.txt", "r")
image = ref_path.read()
decoded_image = base64.b64decode(image)
url = "https://example.com"
headers = {'content-type': 'multipart/form-data'}
files = {
'file1': decoded_image
}
r = requests.post(url, headers=headers, files=files)
print(json.loads(r.text))

测试文件和测试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 '
'filen'
'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 正文拆分为命名序列。

最新更新