代码改变世界

web.py任意文件上传(windows下)

2011-11-20 14:06  会被淹死的鱼  阅读(1748)  评论(0编辑  收藏  举报

web.py是一个python的web框架, 简单易用强大的功能. 以python的方式来写web.

在上传文件上, 我一直遇到点问题, 终于解决了, 记录在这里. 我在网上搜了很久, 这方面的资料好少, 希望可以帮助有需要的人, web.py还是很好用的.

以上都是参考了官方文档, 地址: http://webpy.org/cookbook/index.zh-cn

项目目录格式

说明: upload是上传文件的目录(win7下测试, 图片,文本等都正常), templates是html模板, sqlite.db是sqlite数据库文件, demo.py是源文件. run.bat和READE.txt没什么好说的.

demo.py源代码如下:

import web

urls = (
    '/', 'index',
    '/add', 'add',
    '/upload', 'upload'
)

class index:
    def GET(self):
        todos = db.select('todo')
        return render.index(todos)

class add:
    def POST(self):
        i = web.input()
        n = db.insert('todo', id = i.id, title = i.title)
        raise web.seeother('/')

class upload:
    def POST(self):
        x = web.input(myfile = {})
        filedir = 'images' # change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created
            filepath = x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            filename = filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
            fout = open(filedir +'/'+ filename,'wb') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
#            fout.write(x.myfile.value) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.
        raise web.seeother('/')

app = web.application(urls, globals())
render = web.template.render('templates/')
#db = web.database(dbn='sqlite', db=":memory:")
db = web.database(dbn='sqlite', db="sqlite.db")

conn = db._db_cursor().connection
cursor = conn.cursor()
cursor.execute('DROP TABLE todo')
cursor.execute('''
CREATE TABLE todo (
    id text primary key,
    title text,
    created timestamp,
    done boolean
)
''')

cursor.execute('''
INSERT INTO todo (id, title) VALUES ('01', 'Learn web.py')
''')

cursor.execute('''
INSERT INTO todo (id, title) VALUES ('02', 'Learn python')
''')

conn.commit()

if __name__ == "__main__":
    app.run()

 

上述的代码关键的地方, fout = open(filedir +'/'+ filename,'wb')

官方文档给的例子是打开的模式是'w', 但是下面有一行说明:

[事实上,一定要以"mb"模式打开文件(在windows下), 也就是二进制可写模式, 否则图片将无法上传。]

我之前用w试着运行, 文本文件可以上传, 但是图片等文件, 就会文件错误, 于是修改成二进制文件的方式, 之后就正常了.

 

源代码下载: web.py.zip