Python HTTP – Post a Binary File using urllib2

作者:半瓶墨水   链接:http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/

I was trying to post a png file to our internal webserver for some quick and dirty task, but Python keep throwing ascii encoding exception.

Then I search “post http binary urllib2” and did found several options, like multipart/form-data and pycurl, but they need the webserver’s help to accomplish a simple file posting.

In the end I decide to dig into Python’s httplib and urllib2 to find out what’s going on, if that doesn’t work I will fallback to raw TCP socket solution.

Luckily I got the following solution that works like a charm:
1. set Content-Length header(of the file) before doing post
2. pass a opened file when doing post

Sample code:

Python语言: Python Post a Binary File using urllib2
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

6 条评论 发表在“Python HTTP – Post a Binary File using urllib2”上

  1. littlewater说道:

    改成英文博客了吗- -?

  2. 半瓶墨水说道:

    @littlewater 当时搜索这个问题的时候,发现很多英文的问题(相关的中文问题比较少),所以就发成英文的,希望帮助更多人

  3. 发现很多英文的问题(相关的中文问题比较少),

  4. shankar说道:

    Hi,

    i tried your code. but i need to upload a file to the sharepoint server with basic authendication. Could you please help me for authendication.

    thanks,
    shankar.k

  5. 半瓶墨水说道:

    @shankar
    sharepoint usually uses NTLM authentication instead of basic HTTP authentication

    please refer to:
    1. http://stackoverflow.com/questions/218987/how-can-i-use-sharepoint-via-soap-from-python
    2. http://code.google.com/p/python-ntlm/

  6. 玛雅影视说道:

    :q :)

留下回复