文件上传代码:
[root@linuxyw bottle]# vim main.py
#/usr/bin/env python
#coding=utf-8
from bottle import route, run
from bottle import request
#定义上传路径
save_path = './upload'
#文件上传的HTML模板,这里没有额外去写html模板了,直接写在这里,方便点吧
@route('/upload')
def upload():
return '''
<html>
<head>
</head>
<body>
<form action"/李圆枣upload" method="post" enctype="multipart/form-data">
<input type="file" name="data" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
'''
#文件上传,overwrite=True为覆盖原有的文件,
#如果不加这参数,当服务器已存在同名文件时,将返回“IOError: File exists.”错误
@route('/upload', method = 'POST')
def do_upload():
upload = request.files.get('data')
upload.save(save_path,overwrite=True) #把文件保存到save_path路径下
return 'ok'
run(host='0.0.0.0', port=8080, debug=True)
相关的演示,可自己运行上面代码
此外,上传的文件对象,还有这二个属性
filename :文件名
content_type :文件类型
如上面的代码,上传文件的时候,要获取文件名,就要用upload.filename, 要获取文件类型就用upload.content_type。这二件很实用哪拆,一般要先修改上传的文件名后,再保存到服务器中,content_type则可以检腔锋测文件是什么类型的文件,如果符合我们的上传类型,才保存。
@route('/upload', method = 'POST')
def do_upload():
upload = request.files.get('data')
import os.path
name, ext = os.path.splitext(upload.filename) #用os.path.splitext方法把文件名和后缀相分离
upload.filename = ''.join(('123',ext))#修改文件名
upload.save(save_path,overwrite=True) #把文件保存到save_path路径下
return u'上传成功 原文件名是:%s 文件后缀名是:%s \n 修改后的文件名是:%s' %(name,ext,''.join(('123',ext)))
用浏览器上传文件banner5_6.jpg后,成功显示:
上传成功 原文件名是:banner5_6 文件后缀名是:.jpg 修改后的文件名是:123.jpg
服务器文件结构:
[root@linuxyw bottle]# tree
.
├── main.py
├── upload
│ ├── 11.png
│ ├── 123.jpg
│ └── 23.png
我自己已经解决,册指是官网提供的方案:修改一行代码:
先神盯找到 cxbottle.conf,这个文件,用textedit打开,搜索[EnvironmentVariables],在下面加一行代码:"LC_ALL" = "zh_CN.UTF-8",适用于中文。
如何找cxbottle.conf,
打开设置,C: Drive,往上层走一个文件夹,找到cxbottle.conf。
By default Crossover will get your language and format style from the host operating system. You can manually specify a locale by editing the cxbottle.conf file located in each bottle Crossover creates.
To locate the cxbottle.conf file click the Bottles button in the top-left of the Crossover window, select the appropriate bottle, click the gear menu in the bottom-left and pick Open C: Drive. Go up one level to find the cxbottle.conf file on same directory level as the drive_c folder.
In cxbottle.conf under the EnvironmentVariables section add a new entry for the locale you want to use. For example to set the bottle to Chinese you'd enter:
[EnvironmentVariables]
"LC_ALL"游姿和 = "zh_CN.UTF-8"
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)