webpy 上传文件

x = web.input(myfile={})是一个类字典对象,会返回所有GET或POST的数据

括号内部用来设置myfile的默认值,以防请求中根本就没有myfile键

定义如下一个表单

    form = web.form.Form(
        web.form.Textbox('title', web.form.notnull, 
            size=30,
            description="标题"),
        web.form.Textarea('content', web.form.notnull, 
            rows=8, cols=80,
            description="正文"),
        web.form.File('myfile', description='文件'),
        web.form.Button('button', description='提交'),
    )

 便可通过表单中各元素的名称访问表单的数据

x['title']是一个字符串,而x['myfile']是一个FieldStorage对象

myfile = x['myfile']
myfile.filename #文件标题
myfile.value #文件的二进制数据
myfile.file.read() #同样可以获得文件的二进制数据

对于文件的二进制数据,就像普通文件一样打开一个文件,将数据写入其中,最后关闭就可以了

    filedir = 'upload'
    if file.filename:
        filepath = file.filename.replace('\','/') #问题:文件名中存在路径分隔符?
        fout = open(filedir + '/' + str(num), 'wb')
        fout.write(file.value)
        fout.close()
原文地址:https://www.cnblogs.com/meelo/p/4238146.html