Post a Binary File using urllib2

问题

realfun <[email protected]>
发件人当地时间 发送时间 18:43 (GMT+08:00)。发送地当前时间:下午10:37。 ✆
发送至     [email protected]
日期      2011年3月30日 下午6:43
主题      [CPyUG] Python怎么做比较简单的POST Binary数据?

写了一个脚本需要POST一个图片到服务器,服务器只接受Content-Type为image/png

'ascii' codec can't decode byte 0x89 in position 0: ordinal not in range(128)

(个人觉得python的编码很混乱,像这样的函数不应该再在内部做编码解码了)

我查到了一些资料,好像都需要改Content-Type才行:

还试过base64编码以后加上header,但是也没用 request.add_header('Content-Transfer-Encoding', 'base64')

解决

realfun <[email protected]>
发件人当地时间 发送时间 22:34 (GMT+08:00)。发送地当前时间:下午10:36。 ✆
发送至     [email protected]
主题      Re: [CPyUG] Python怎么做比较简单的POST Binary数据?

   1 import urllib2, os
   2 
   3 image_path = "png\\01.png"
   4 url = 'http://xx.oo.com/webserviceapi/postfile/'
   5 length = os.path.getsize(image_path)
   6 png_data = open(image_path, "rb")
   7 request = urllib2.Request(url, data=png_data)
   8 request.add_header('Cache-Control', 'no-cache')
   9 request.add_header('Content-Length', '%d' % length)
  10 request.add_header('Content-Type', 'image/png')
  11 res = urllib2.urlopen(request).read().strip()
  12 return res


反馈

创建 by -- ZoomQuiet [2011-03-30 14:38:54]

MiscItems/2011-03-30 (last edited 2011-03-30 14:38:53 by ZoomQuiet)