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:
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
共 5 条评论
发表评论
Additional comments powered by BackType



改成英文博客了吗- -?
@littlewater 当时搜索这个问题的时候,发现很多英文的问题(相关的中文问题比较少),所以就发成英文的,希望帮助更多人
发现很多英文的问题(相关的中文问题比较少),
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
@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/