![](/img/trans.png)
[英]Python - How to send base64 data from MongoDB to Multipart-form API
[英]How to send multipart/form file from 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 '
'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 正文拆分為命名序列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.