Python:使用图像文件发布请求
我有一个服务器,我正试图建立一个post请求来获取数据。我认为实现这一点的一种方法是在报头中添加参数并发出请求。但我得到了一些错误,我不太明白,继续前进 Html表单Python:使用图像文件发布请求,python,post,request,urllib2,urllib,Python,Post,Request,Urllib2,Urllib,我有一个服务器,我正试图建立一个post请求来获取数据。我认为实现这一点的一种方法是在报头中添加参数并发出请求。但我得到了一些错误,我不太明白,继续前进 Html表单 <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> </head> <body> <form method="POST" ac
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="POST" action="http://some.server.com:61235/imgdigest" enctype="multipart/form-data">
quality:<input type="text" name="quality" value="2"><br>
category:<input type="text" name="category" value="1"><br>
debug:<input type="text" name="debug" value="1"><br>
image:<input type="file" name="image"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
错误:
page = urllib2.urlopen(request)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 406, in open
response = meth(req, response)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 519, in http_response
'http', request, response, code, msg, hdrs)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 444, in error
return self._call_chain(*args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 378, in _call_chain
result = func(*args)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found
在此标题中添加一个标题:
request.add_header("Content-type", "application/x-www-form-urlencoded; charset=UTF-8")
此外,要发送的图像参数是字符串,而不是图像文件的内容。你需要对它进行b64编码
import base64
with open("image.jpg", "rb") as image_file:
encoded_image = base64.b64encode(image_file.read())
然后使用
encoded\u image
而不是raw\u params
中的“~/image.jpg
”。首先,图像需要是图像,而不是字符串。我建议尝试请求,而不是使用urllib、urllib2。因此,我应该在request=urllib2.request(page,params)之后将其添加到标题中?确保python代码中使用的url与html表单中的action属性完全相同。看起来您正在python.ok中添加“.html”,但请注意url仍然不一样,在python中有:page='',在html中有:。。。
import base64
with open("image.jpg", "rb") as image_file:
encoded_image = base64.b64encode(image_file.read())