码迷,mamicode.com
首页 > Web开发 > 详细

bottle框架学习(五)之文件的下载与上传

时间:2015-06-21 15:58:27      阅读:589      评论:0      收藏:0      [点我收藏+]

标签:bottle   python   上传与下载   linux   web开发   网站   

下载文件

Bottle文件下载还是使用static_file这个模块,只是多加了一个参数:download=True,还是看例子吧!

[root@jubottle]# cat download.py
#!/usr/bin/envpython
#coding=utf-8
frombottle import route,run,view,static_file
 
@route(‘/download/<filename:path>‘)
defdownload(filename):
    returnstatic_file(filename,root=‘/home/bottle/static‘,download=True)
run(host=‘0.0.0.0‘,port=8000,debug=True)
[root@jubottle]# ll static/
总用量 100
-rw-r--r--.1 root root 67886 6月  20 2015 lufei.jpg
-rw-r--r--.1 root root 30973 6月  21 2015 suolong.jpg

在浏览器中输入:http://192.168.116.199:8000/download/suolong.jpg

技术分享

 

上面是使用URL直接下载,下面演示使用链接下载:

[root@jubottle]# cat download.py
#!/usr/bin/envpython
#coding=utf-8
frombottle import route,run,template,static_file
 
@route(‘/download/<filename:path>‘)
defdownload(filename):
   returnstatic_file(filename,root=‘/home/bottle/static‘,download=filename)
 
@route(‘/hello‘)
defhello():
    return template(‘hello‘)
run(host=‘0.0.0.0‘,port=8000,debug=True)
[root@jubottle]# cat views/hello.tpl
<html>
    <head>
    <title>Download Test!</title>
    </head>
    <body>
    <ahref="/download/lufei.jpg">下载文件</a>
    </body>
</html>

在浏览器中输入:http://192.168.116.199:8000/hello,然后点击下载文件

技术分享

 

上传文件

上传文件时在前端form表单中,要添加enctype="multipart/form-data"属性,enctype="multipart/form-data"的意思,是设置表单的MIME 编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传,只有使用了multipart /form-data,才能完整的传递文件数据。

在后端,用request.files方法,获取到表单传上来的文件,首先把对象赋值给一个变量名,如uploadfile,然后用save()的方法来保存到服务器中。uploadfile.save(save_path,overwrite=True)save_path是保存文件的路径,overwrite=True是指如果服务器的上传目录中已有同名文件存在,则覆盖。

[root@jubottle]# cat upload.py
#!/usr/bin/envpython
#coding=utf-8
frombottle import route,run,template,request
 
upload_path=‘./static‘#定义上传文件的保存路径
@route(‘/upload‘)
defupload():
    return template(‘upload‘) #使用get方法会返回这个模版
 
@route(‘/upload‘,method=‘POST‘)
defdo_upload():
    uploadfile=request.files.get(‘data‘) #获取上传的文件
    uploadfile.save(upload_path,overwrite=True)#overwrite参数是指覆盖同名文件
    return u"上传成功,文件名为:%s,文件类型为:%s"% (uploadfile.filename,uploadfile.content_type)
    #filename是获取上传文件文件名,content_type是获取上传的文件类型
run(host=‘0.0.0.0‘,port=8000,debug=True)
[root@jubottle]# cat views/upload.tpl
<html>
    <head>
    <title>Upload Test!</title>
    </head>
    <body>
    <form action="upload"method="POST" enctype="multipart/form-data">
    <input type="file"name="data" />
    <input type="submit"value="Upload" />
    </form>
    </body>
</html>

在浏览器中输入:http://192.168.116.199:8000/upload

技术分享

点击浏览上传文件 

技术分享

本文出自 “乾楠有” 博客,请务必保留此出处http://changfei.blog.51cto.com/4848258/1663965

bottle框架学习(五)之文件的下载与上传

标签:bottle   python   上传与下载   linux   web开发   网站   

原文地址:http://changfei.blog.51cto.com/4848258/1663965

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!