详解python上传文件和字符到PHP服务器
很多朋友在留言区询问关于python上传文件和字符到服务器的问题,现编针对这个给大家整理了一个解决办法。
上传简单的字符串
defsend_str_server(self):
payload={'key1':'value1','key2':'value2'}
r=requests.post("http://httpbin.org/post",
data=payload)
介绍:payload为键值对形式的数据,在服务器的数据的显示为
key1=value1&key2=value2
http://httpbin.org/post为上传的服务器地址
上传文件
defsend_image_server(self):
data={"k1":"v1"}
files={"img":open("test.png","rb")}
r=requests.post("http://httpbin.org/post",data,
files=files)
介绍:data为键值对形式的数据,为post请求携带的数据
files中的img表示的是php服务器中对图片的过滤字段,open中第一个参数为图片的地址,第二个参数表示二进制文件写的权限,http://httpbin.org/post是服务器的地址
pythonpost方式上传文件到php服务器
看了网上很多代码,都没有说如何具体的使用poster,试了两天,终于成功了
通过python调用php实现了文件上传
与大家分享一下:
首先要通过pip安装poster(easy_install也是一样的):
pipinstallposter
image.py
#!usr/bin/python
#image.py
#-*-coding=utf-8-*-
fromposter.encodeimportmultipart_encode
importurllib2
importsys
fromurllib2importRequest,urlopen,URLError,HTTPError
fromposter.encodeimportmultipart_encode
fromposter.streaminghttpimportregister_openers
register_openers()
f=open(“C:/Users/User/Pictures/SavedPictures/test1.jpg”,"rb")
#f=open(sys.argv[1],"rb")使用sys.argv[1]可调用参数例如运行pythonimage.pyC:/Users/User/Pictures/SavedPictures/test1.jpg
#可将test1.jpg作为参数传入image.py
#"C:/Users/User/Pictures/SavedPictures/vedio5.jpg"
#headers包含必须的Content-Type和Content-Length
#datagen是一个生成器对象,返回编码过后的参数
datagen,headers=multipart_encode({"myFile":f})
#创建请求对象
request=urllib2.Request("http://localhost/upload_image/upload_image.php",datagen,headers)
try:
response=urllib2.urlopen(request)
printresponse.read()
exceptURLError,e:
printe.reason
printe.code
-----
upload_image.php
----
以上就是小编亲测的关于python上传和文件和字符到PHP服务器的代码实现的两种方式,如果大家还有更好的内容可以在下方留言给我们,一起交流一下。