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好,一统天下了,不过貌似浪费了很多空间。嗯,编码方案,要再细细研究研究。
- web.py文件上传实例
- Web.py中的文件上传
- web.py 0.3 - 无废话实例
- web.py自定义not found 实例
- web 编程中实现文件上传的服务端实例
- 【Java.Web】Servlet —— 实例 之 上传文件
- bottle.py 实现批量文件上传
- Struts2 上传文件实例
- Jftp上传文件实例
- java上传文件实例
- Excel文件上传实例
- 上传文件实例01
- 文件的上传实例
- 文件上传Servlet实例
- 文件上传实例
- struts2文件上传实例
- Struts2文件上传实例
- 文件上传实例
- 封装了一些辅助类
- Cocos2d-x学习之创建Android工程和编译
- 【转】博弈论--取物品和Nim游戏
- uva 10603 Fill
- 整站源码测试之一
- web.py文件上传实例
- 5.View学习(Official Tutorials)
- Quantization
- 高效程序员的 7 个共同特征
- Word另存HTML最可靠的方法
- 关于图像特征提取
- Palindrome Partitioning II
- The Trick To Good Software
- C#继承中的关键字 virtual、override 与new