Python实现基于HTTP文件传输实例
程序员文章站
2023-12-14 18:54:10
本文实例讲述了python实现基于http文件传输的方法。分享给大家供大家参考。具体实现方法如下:
一、问题:
因为需要最近看了一下通过post请求传输文件的内容 并且...
本文实例讲述了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程序设计有所帮助。