python http上传文件处理示例

<HTML>

<FORM ACTION='cgi-bin/action.py' METHOD='POST' enctype='multipart/form-data'>
    <input type='hidden' name='user' value='lola'>
    <input type='hidden' name='action' value='upload'>
    <BR><I>FILE:</I> <INPUT TYPE='FILE' NAME=upfile>
<br>
<input type='submit' value='Press'> to upload the file!
</form>

</HTML>

File:action.py

#!c:/Python25/python

import cgi
import sys

def gen_html_header() :
    print 'Content-Type: text/html\n\n'
    print '<HTML>'

def gen_html_trailer() :
    print '</HTML>'
gen_html_header()
form = cgi.FieldStorage()
try :
    file_contents = form['upfile'].value
    print file_contents
except :
    print sys.exc_info()

gen_html_trailer()

编程技巧