##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = Post a Binary File using urllib2 = ##startInc == 问题 == {{{ realfun 发件人当地时间 发送时间 18:43 (GMT+08:00)。发送地当前时间:下午10:37。 ✆ 发送至 python-cn@googlegroups.com 日期 2011年3月30日 下午6:43 主题 [CPyUG] Python怎么做比较简单的POST Binary数据? }}} 写了一个脚本需要POST一个图片到服务器,服务器只接受Content-Type为image/png * 直接用urllib2的open或者urlopen做post的话,会出现编码错误: {{{ 'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128) }}} (个人觉得python的编码很混乱,像这样的函数不应该再在内部做编码解码了) 我查到了一些资料,好像都需要改Content-Type才行: * http://code.activestate.com/recipes/146306/ * http://blog.doughellmann.com/2009/07/pymotw-urllib2-library-for-opening-urls.html * http://pycurl.sourceforge.net/ 还试过base64编码以后加上header,但是也没用 `request.add_header('Content-Transfer-Encoding', 'base64')` == 解决 == {{{ realfun 发件人当地时间 发送时间 22:34 (GMT+08:00)。发送地当前时间:下午10:36。 ✆ 发送至 python-cn@googlegroups.com 主题 Re: [CPyUG] Python怎么做比较简单的POST Binary数据? }}} {{{ #!python import urllib2, os image_path = "png\\01.png" url = 'http://xx.oo.com/webserviceapi/postfile/' length = os.path.getsize(image_path) png_data = open(image_path, "rb") request = urllib2.Request(url, data=png_data) request.add_header('Cache-Control', 'no-cache') request.add_header('Content-Length', '%d' % length) request.add_header('Content-Type', 'image/png') res = urllib2.urlopen(request).read().strip() return res }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]