Home >Backend Development >Python Tutorial >Python实现基于HTTP文件传输实例

Python实现基于HTTP文件传输实例

WBOY
WBOYOriginal
2016-06-06 11:20:401974browse

本文实例讲述了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 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

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn