Python实现基于HTTP文件传输实例
本文实例讲述了Python实现基于HTTP文件传输的方法。分享给大家供大家参考。具体实现方法如下:
一、问题:
因为需要最近看了一下通过POST请求传输文件的内容 并且自己写了Server和Client实现了一个简单的机遇HTTP的文件传输工具
二、实现代码:
Server端:
复制代码 代码如下:
#coding=utf-8
from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
}
)
self.send_response(200)
self.end_headers()
self.wfile.write('Client: %sn ' % str(self.client_address) )
self.wfile.write('User-agent: %sn' % str(self.headers['user-agent']))
self.wfile.write('Path: %sn'%self.path)
self.wfile.write('Form data:n')
for field in form.keys():
field_item = form[field]
filename = field_item.filename
filevalue = field_item.value
filesize = len(filevalue)#文件大小(字节)
print len(filevalue)
with open(filename.decode('utf-8')+'a','wb') as f:
f.write(filevalue)
return
if __name__=='__main__':
from BaseHTTPServer import HTTPServer
sever = HTTPServer(('localhost',8080),PostHandler)
print 'Starting server, use <Ctrl-C> to stop'
sever.serve_forever()
from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
}
)
self.send_response(200)
self.end_headers()
self.wfile.write('Client: %sn ' % str(self.client_address) )
self.wfile.write('User-agent: %sn' % str(self.headers['user-agent']))
self.wfile.write('Path: %sn'%self.path)
self.wfile.write('Form data:n')
for field in form.keys():
field_item = form[field]
filename = field_item.filename
filevalue = field_item.value
filesize = len(filevalue)#文件大小(字节)
print len(filevalue)
with open(filename.decode('utf-8')+'a','wb') as f:
f.write(filevalue)
return
if __name__=='__main__':
from BaseHTTPServer import HTTPServer
sever = HTTPServer(('localhost',8080),PostHandler)
print 'Starting server, use <Ctrl-C> to stop'
sever.serve_forever()
Client端:
复制代码 代码如下:
#coding=utf-8
import requests
url = 'http://localhost:8080'
path = u'D:快盘阿狸头像.jpg'
print path
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print r.url,r.text
import requests
url = 'http://localhost:8080'
path = u'D:快盘阿狸头像.jpg'
print path
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print r.url,r.text
希望本文所述对大家的Python程序设计有所帮助。