sunfull 发表于 2015-12-15 11:47:13

在windows下使用python的CGIHTTPServer实现文件上传网页浏览

什么是CGI
CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口。

网页浏览
为了更好的了解CGI是如何工作的,我们可以从在网页上点击一个链接或URL的流程:

[*]1、使用你的浏览器访问URL并连接到HTTP web 服务器。
[*]2、Web服务器接收到请求信息后会解析URL,并查找访问的文件在服务器上是否存在,如果存在返回文件的内容,否则返回错误信息。
[*]3、浏览器从服务器上接收信息,并显示接收的文件或者错误信息。
CGI程序可以是Python脚本,PERL脚本,SHELL脚本,C或者C++程序等。

如何在windows上使用python搭建简单的http服务器呢?

首先,在电脑的任意目录下新建一个文件夹,我命名为www,然后在该目录下新建一个子文件夹cgi-bin(注意此处的文件夹名必须是这个)。

其次,在www文件夹的目录下打开命令行,输入python -m CGIHTTPServer,如下图

默认的是接听8000端口,也可以通过自己设置参数修改。

然后将负责接收文件的脚本放入cgi-bin目录下,就可以实现文件上传了。

实例代码:
文件上传html文件



[*]

[*]
[*]
[*]
[*]Filename:
[*]
[*]
[*]
[*]
[*]
[*]
[*]

接收文件代码www/cgi-bin/server.py



[*]#!/usr/bin/python

[*]#coding=utf-8
[*]# Import modules for CGI handling
[*]import cgi, os
[*]import cgitb; cgitb.enable()
[*]#import facedetectme
[*]form = cgi.FieldStorage()
[*]# Get filename here.
[*]fileitem = form['img']
[*]# Test if the file was uploaded
[*]if fileitem.filename:
[*]   # strip leading path from file name to avoid
[*]   # directory traversal attacks
[*]   fn = os.path.basename(fileitem.filename)
[*]   open('C:/Users/window7/Desktop/www/cgi-bin/' + "1.jpg", 'wb').write(fileitem.file.read())
[*]   message = 'The file "' + fn + '" was uploaded successfully'
[*]
[*]else:
[*]   message = 'No file was uploaded'
[*]print """\

[*]Content-Type: text/html\n
[*]
[*]
[*]     %s
[*]
[*]
[*]""" % (message,)
[*]
[*]#facedetectme.detect_draw_Faces("4.jpg")
页: [1]
查看完整版本: 在windows下使用python的CGIHTTPServer实现文件上传网页浏览