gpt4 book ai didi

python - 如何在python 3中发送post文件(图像)

转载 作者:行者123 更新时间:2023-11-30 23:07:51 25 4
gpt4 key购买 nike

首先请原谅我的英语不好(我说西类牙语)。

我正在尝试提交带有图像上传的表单。

当我想发送普通数据(如何文本字符串)时,我这样做:

首先导入模块:

import urllib.request

import urllib.parse

import http.cookiejar

准备 cookie 和 header :

cj = http.cookiejar.CookieJar()
open = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
abriendo.addheaders = [("User-agent","Mozilla/5.0")]
urllib.request.install_opener(open)

对 url 数据进行编码,我使用 id(它位于 Web 表单 html 中)

valor1 = {"username":"test1","password","hello"}
valor2 = urllib.parse.urlencode(valor1)
finalvalor = valor2.encode("UTF-8")

现在可以发送发布数据(记住,这是一个带有字符串数据的示例)

nav = urllib.request.urlopen(url,finalvalor)
navread = str(nav.read())

Url 变量包含帖子 url

这很好用,但我在发送图像时遇到问题。

网络表单以以下代码开始:

 <form enctype="multipart/form-data" onsubmit="return ver('espera');"
action="example.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="5300000">
<br><br>
<div align="center" id="uploadFileContainer">
<input size="25" id="uploadFile1" name="uploadFile1" type="file">

我愿意

dicc = {"uploadFile1":open("1.jpg","rb")}
nav = urllib.request.urlopen(url,dicc)
navread = str(nav.read())

出现此错误:

ValueError: Content-Length should be specified for iterable data of type <class 'dict'> {'uploadFile1': <_io.BufferedReader name='1.jpg'>

我尝试对数据进行编码( enconde dicc 如何正常 url )但不起作用(不发送任何数据)。我在 googe 上冲浪,我认为二进制数据需要编码为 base64 ??

最后问题是,如何使用urllib.request模块上传图片?

感谢您的阅读。

最佳答案

在 python 中发送文件的简单方法是使用 requests 库:

import requests
files = {'file': open('1.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.text)

比照requests' documentation 。它基本上可以完成您尝试做的所有事情,但使其变得简单且非常Pythonic。

关于python - 如何在python 3中发送post文件(图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32029545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com