web.py文件上传实例

来源:互联网 发布:吉首大学网络课 编辑:程序博客网 时间:2024/06/05 00:15

都说Django是重量级的web框架,而web.py是轻量级的,django给我印象最深刻的还是它的admin管理,由于是django自带的,其它方面还没看出来怎么样,但是web.py也很有趣,写起应用来,短小而精悍。

官网上有一个文件上传的示例程序,代码如下:

import weburls = ('/upload', 'Upload')class Upload:    def GET(self):        web.header("Content-Type","text/html; charset=utf-8")        return """<html><head></head><body><form method="POST" enctype="multipart/form-data" action=""><input type="file" name="myfile" /><br/><input type="submit" /></form></body></html>"""    def POST(self):        x = web.input(myfile={})        filedir = '/path/where/you/want/to/save' # 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,'w') # 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.close() # closes the file, upload complete.        raise web.seeother('/upload')if __name__ == "__main__":   app = web.application(urls, globals())    app.run()
(html文字还是模板的形式比较好)。
在windows下小试了一把,发现在上传中文名文件时会出现乱码,以为是程序的编码出问题了,于是把程序的编码改成了uft8,在程序开头加了几句

default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding:     reload(sys)     sys.setdefaultencoding(default_encoding) 

结果还是不行,纳闷了,于是查看了一下文件名保存后的编码方案,还是utf-8,由于我是在xp运行的,文件上传保存在本机上,这下找着原因了,原来是windows不认识utf-8编码的汉字了,于是加上一句

 filename = filename.encode("gb2312")
结果汉字就是汉字了,没有乱码。看来文字的编码方式在网络传输中很重要。这让我想到了协议,类似于printf函数参数入栈顺序,printf的参数是从左到右入栈,而printf的函数调用方以从右至左的入栈顺序去识别它,那肯定就会出错了,一点联想。

关于文字编码的问题我已经遇到不止一次了,前有mysql不能正常显示汉字,php页面文字乱码,还是unicode好,一统天下了,不过貌似浪费了很多空间。嗯,编码方案,要再细细研究研究。


原创粉丝点击