如何在 Python 中模拟 post 表单来上传文件
3个回答
推荐于2016-09-15 · 知道合伙人互联网行家
关注
展开全部
在机器上安装了Python的setuptools工具,可以通过下面的命令来安装 poster:
easy_install poster
装完之后,安装下面代码就可以实现post表单上传文件了:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
# 在 urllib2 上注册 http 流处理句柄
register_openers()
# 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码
# "image1" 是参数的名字,一般通过 HTML 中的 <input> 标签的 name 参数设置
# headers 包含必须的 Content-Type 和 Content-Length
# datagen 是一个生成器对象,返回编码过后的参数
datagen, headers = multipart_encode({"image1": open("DSC0001.jpg", "rb")})
# 创建请求对象(localhost服务器IP地址,5000服务器端口)
request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)
# 实际执行请求并取得返回
print urllib2.urlopen(request).read()
展开全部
发个以前用urllib2模块来做的
class HTTPError(urllib2.HTTPDefaultErrorHandler):
def __init__(self):
self.errMsg = ''
def getErrorMsg(self):
return self.errMsg
def http_error_default(self, req, fp, code, msg, hdrs):
if code >= 400 :
self.errMsg = fp.read()
raise urllib2.HTTPError(req.get_full_url(), code, msg, hdrs, fp)
'''
urllib2 post request: eg. uploadfile
'''
def sendMultipartPost(url, params, files):
#params like this :{'type':'upload','id':'xxxx'}
#files like this: {'file':'C:/xxxx.txt'}
posterParams = []
for key in params:
value = params[key]
try:
posterParams.append(poster.encode.MultipartParam(key, value))
except Exception, e:
print e, key, value
raise e
for key in files:
value = files[key]
try:
value = value.encode(sys.getfilesystemencoding())
posterParams.append(poster.encode.MultipartParam.from_file(key, value))
except Exception, e:
print e, key, value
raise e
try:
datagen, headers = poster.encode.multipart_encode(posterParams)
except Exception, e:
print e, key, value
raise e
if headers is None:
headers = {}
try:
request = urllib2.Request(url, datagen, headers)
request.add_header('Accept-encoding', 'gzip')
request.add_header("Accept", "*/*")
# print request
# print request.get_data()
opener,err = getUrllib2(True, False)
response = opener.open(request)
except Exception, e:
print e, url, files
print err.getErrorMsg()
raise e
data = response.read()
'''
data = response.read(16*1024)
length = len(data)
_data = None
while length:
if _data: data += _data
_data = response.read(16*1024)
length = len(_data)
'''
if 'gzip' == response.headers.get('content-encoding', ''):
compressedstream = StringIO.StringIO(data)
gzipper = gzip.GzipFile(fileobj=compressedstream)
data =gzipper.read()
return data
def getUrllib2(upload = False, redirect = False):
if upload:
handlers = poster.streaminghttp.get_handlers()
else:
handlers = []
err = HTTPError()
handlers.append(err)
handlers.append(getCookie())
try:
opener = urllib2.build_opener(*handlers)
except Exception, e:
print err.getErrorMsg()
raise e
return opener,err
def getCookie():
global _cookieProcessor
cookiefile = "./cookies.txt"
try:
httpcookie = cookielib.MozillaCookieJar(cookiefile)
httpcookie.load(ignore_discard=True, ignore_expires=True)
httpcookie = urllib2.HTTPCookieProcessor(httpcookie)
except Exception, e:
print e
httpcookie = _cookieProcessor
# _cookieProcessor = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
return httpcookie
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
Python-Requests 非常方便。
我的某个上传文件代码(是的,multipart / form-data 上传就这一行)
r = requests.post (server('new'), files={'content' : open('test.md', 'rb')})
我的某个上传文件代码(是的,multipart / form-data 上传就这一行)
r = requests.post (server('new'), files={'content' : open('test.md', 'rb')})
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询