服务器代码:
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
import cgi
import os class MyHTTPRequestHandler( BaseHTTPRequestHandler ): def do_GET( self ): pass def do_POST(self): form = cgi.FieldStorage( # cgi.FieldStorage实例效果类似一个字典,包含键-值和len等内置函数
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
print self.headers['Content-Type'] self.send_response(200)
self.end_headers()
self.wfile.write('Client: %s\n' % str(self.client_address))
# self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
# self.wfile.write('Path: %s\n' % self.path) params = {}
for field in form.keys():
params[field] = form[field].value fpth = params.get('f')
data = params.get('d')
code = params.get('c') try:
result = self.filesave(fpth, data, code)
except Exception, e:
result = 'Error in filesave:%s' % e
finally:
self.wfile.write(result) def filesave(self, fpth, data, code): if (fpth and data and code) is None:
return 'Params uncomplete!\n' path = '/'.join(fpth.split('/')[:-1])
name = fpth.split('/')[-1]
if not os.path.exists(path):
os.makedirs(path)
f = open(fpth, 'w')
f.write(data.encode(code))
f.close()
return 'Filesaved in %s' % fpth def do_HEAD( self ): pass if __name__ == '__main__': port = 28080
httpd = HTTPServer(('', port ), MyHTTPRequestHandler)
print "Server is running at port", port
httpd.serve_forever()
测试网页:
<!Doctype html>
<html xmlns=http://www.w3.org/1999/xhtml>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<meta http-equiv=X-UA-Compatible content=IE=EmulateIE7>
<title>百度一下,你就知道 </title>
<form name="f" id="s_ps_form" action="http://localhost:28080/" method="post" target='bbbb' > <input type="text" name="f" id="kw" maxlength="100" style="width:474px;" >
<input type="text" name="d" id="kw" maxlength="100" style="width:474px;" >
<input type="text" name="c" id="kw" maxlength="100" style="width:474px;" >
<input type="text" name="u" id="kw" maxlength="100" style="width:474px;" > <input type="submit" value="百度一下"> </form> <iframe name='bbbb'></iframe>
效果: