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

yipeiwu_com6年前Python基础

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

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程序设计有所帮助。

相关文章

Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】

本文实例讲述了Python二叉树的遍历操作。分享给大家供大家参考,具体如下: # coding:utf-8 """ @ encoding: utf-8 @ author: lixia...

python requests指定出口ip的例子

爬虫需要,一个机器多个口,一个口多个ip,为轮询这些ip demo #coding=utf-8 import requests,sys,socket from requests_to...

python实现多线程采集的2个代码例子

代码一: #!/usr/bin/python # -*- coding: utf-8 -*- #encoding=utf-8   import threading impo...

Python分支结构(switch)操作简介

Python当中并无switch语句,本文研究的主要是通过字典实现switch语句的功能,具体如下。 switch语句用于编写多分支结构的程序,类似与if….elif….else语句。...

python调用cmd复制文件代码分享

复制代码 代码如下:import os def load() :    filename = os.getcwd() + r'\fromto.txt'&nb...