前面已经在一篇文章《试用Pycurl》中简单介绍过pycurl了,这次因为做一个小功能,又用pycurl用post请求上传了一个文件。(PS:接收该上传的服务器端是一个简单的PHP程序,前面这篇文章已经介绍了一下《PHP实现文件上传功能》。
我写的一个上传图片的函数如下:
def upload_img(self, mypic):
'''
upload the image to the remote server.
'''
storage = StringIO()
c = pycurl.Curl()
values = [
("upload_file[]", (pycurl.FORM_FILE, str(mypic)))
]
c.setopt(c.URL, self.upload_url)
c.setopt(c.WRITEFUNCTION, storage.write)
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
content = storage.getvalue()
print content
其中,mypic就是一个本地图片的路径,storage变量是为了存储post后返回的相应信息。
相对完整的一个程序,在:https://github.com/smilejay/python/blob/master/py2014/app_poi.py
参考资料:
http://pycurl.cvs.sourceforge.net/pycurl/pycurl/tests/test_post2.py?view=markup