歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> web.py任意文件上傳(Windows下)

web.py任意文件上傳(Windows下)

日期:2017/3/1 10:48:53   编辑:Linux編程

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試著運行, 文本文件可以上傳, 但是圖片等文件, 就會文件錯誤, 於是修改成二進制文件的方式, 之後就正常了.

源代碼下載:

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /pub/2011/12/12/web.py任意文件上傳(Windows下)/

Copyright © Linux教程網 All Rights Reserved