python上传文件

来源:互联网 发布:淘宝网秒杀系统异常 编辑:程序博客网 时间:2024/06/04 18:12

http://www.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file


pip install requests



>>> url = 'http://httpbin.org/post'>>> files = {'file': open('report.xls', 'rb')}>>> r = requests.post(url, files=files)>>> r.text


但经测试上传时php无法识别file['type'],须手动添加参数

>>> files = {'file': ('report.xls', open('report.xls', 'rb'),'image/png')}




---------------------------------------------------------

http://oldj.net/article/python-upload-file-via-form-post/




easy_install poster

or

pip install poster







# test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
 
# 在 urllib2 上注册 http 流处理句柄
register_openers()
 
# 开始对文件 "DSC0001.jpg" 的 multiart/form-data 编码
# "image1" 是参数的名字,一般通过 HTML 中的 <input> 标签的 name 参数设置
 
# headers 包含必须的 Content-Type 和 Content-Length
# datagen 是一个生成器对象,返回编码过后的参数
datagen, headers=multipart_encode({"image1":open("DSC0001.jpg","rb")})
 
# 创建请求对象
request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)
# 实际执行请求并取得返回
printurllib2.urlopen(request).read()




0 1