Python使用Flask框架同时上传多个文件的方法


Posted in Python onMarch 21, 2015

本文实例讲述了Python使用Flask框架同时上传多个文件的方法,分享给大家供大家参考。具体如下:

下面的演示代码带有详细的html页面和python代码

import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
# Initialize the Flask application
app = Flask(__name__)
# This is the path to the upload directory
app.config['UPLOAD_FOLDER'] = 'uploads/'
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
  return '.' in filename and \
      filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/')
def index():
  return render_template('index.html')
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
  # Get the name of the uploaded files
  uploaded_files = request.files.getlist("file[]")
  filenames = []
  for file in uploaded_files:
    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
      # Make the filename safe, remove unsupported chars
      filename = secure_filename(file.filename)
      # Move the file form the temporal folder to the upload
      # folder we setup
      file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
      # Save the filename into a list, we'll use it later
      filenames.append(filename)
      # Redirect the user to the uploaded_file route, which
      # will basicaly show on the browser the uploaded file
  # Load an html page with a link to each uploaded file
  return render_template('upload.html', filenames=filenames)
 
# This route is expecting a parameter containing the name
# of a file. Then it will locate that file on the upload
# directory and show it on the browser, so if the user uploads
# an image, that image is going to be show after the upload
@app.route('/uploads/<filename>')
def uploaded_file(filename):
  return send_from_directory(app.config['UPLOAD_FOLDER'],
                filename)
if __name__ == '__main__':
  app.run(
    host="0.0.0.0",
    port=int("80"),
    debug=True
  )

index.html代码

<!DOCTYPE html>
<html lang="en">
 <head>
  <link href="bootstrap/3.0.0/css/bootstrap.min.css"
  rel="stylesheet">
 </head>
 <body>
  <div class="container">
   <div class="header">
    <h3 class="text-muted">How To Upload a File.</h3>
   </div>
   <hr/>
   <div>
   <form action="upload" method="post" enctype="multipart/form-data">
   <input type="file" multiple="" name="file[]" class="span3" /><br/>
    <input type="submit" value="Upload" class="span2">
   </form>
   </div>
  </div>
 </body>
</html>

upload.html页面:

<!DOCTYPE html>
<html lang="en">
 <head>
  <link href="bootstrap/3.0.0/css/bootstrap.min.css"
     rel="stylesheet">
 </head>
 <body>
  <div class="container">
   <div class="header">
    <h3 class="text-muted">Uploaded files</h3>
   </div>
   <hr/>
   <div>
   This is a list of the files you just uploaded, click on them to load/download them
   <ul>
    {% for file in filenames %}
     <li><a href="{{url_for('uploaded_file', filename=file)}}">{{file}}</a></li>
    {% endfor %}
   </ul>
   </div>
   <div class="header">
    <h3 class="text-muted">Code to manage a Upload</h3>
   </div>
   <hr/>  
<pre>
@app.route('/upload', methods=['POST'])
def upload():
  # Get the name of the uploaded file
  #file = request.files['file']
  uploaded_files = request.files.getlist("file[]")
  filenames = []
  for file in uploaded_files:
    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
      # Make the filename safe, remove unsupported chars
      filename = secure_filename(file.filename)
      # Move the file form the temporal folder to the upload
      # folder we setup
      file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
      filenames.append(filename)
      # Redirect the user to the uploaded_file route, which
      # will basicaly show on the browser the uploaded file
  # Load an html page with a link to each uploaded file
  return render_template('upload.html', filenames=filenames)
</pre>
   </div>
  </div>
 </body>
</html>

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python虚拟环境Virtualenv使用教程
May 18 Python
Python3.4解释器用法简单示例
Mar 22 Python
在python中利用numpy求解多项式以及多项式拟合的方法
Jul 03 Python
python numpy之np.random的随机数函数使用介绍
Oct 06 Python
python中dict()的高级用法实现
Nov 13 Python
django中media媒体路径设置的步骤
Nov 15 Python
在Python中利用pickle保存变量的实例
Dec 30 Python
python剪切视频与合并视频的实现
Mar 03 Python
Python读写操作csv和excle文件代码实例
Mar 16 Python
解决Keras 自定义层时遇到版本的问题
Jun 16 Python
python+selenium爬取微博热搜存入Mysql的实现方法
Jan 27 Python
python+pyhyper实现识别图片中的车牌号思路详解
Dec 24 Python
python中Flask框架简单入门实例
Mar 21 #Python
python中django框架通过正则搜索页面上email地址的方法
Mar 21 #Python
Python去除列表中重复元素的方法
Mar 20 #Python
python在windows下实现ping操作并接收返回信息的方法
Mar 20 #Python
Python实现微信公众平台自定义菜单实例
Mar 20 #Python
python在windows和linux下获得本机本地ip地址方法小结
Mar 20 #Python
python使用三角迭代计算圆周率PI的方法
Mar 20 #Python
You might like
发布一个迷你php+AJAX聊天程序[聊天室]提供下载
2007/07/21 PHP
php ajax 静态分页过程形式
2011/09/02 PHP
Mootools 1.2教程 类(一)
2009/09/15 Javascript
javascript 判断中文字符长度的函数代码
2012/08/27 Javascript
web性能优化之javascript性能调优
2012/12/28 Javascript
jCallout 轻松实现气泡提示功能
2013/09/22 Javascript
js获取指定的cookie的具体实现
2014/02/20 Javascript
基于jquery实现即时检查格式是否正确的表单
2016/05/06 Javascript
轻松实现js弹框显示选项
2016/09/13 Javascript
详解webpack 入门总结和实践(按需异步加载,css单独打包,生成多个入口文件)
2017/06/20 Javascript
Angular.js中数组操作的方法教程
2017/07/31 Javascript
Javascript Promise用法详解
2018/05/10 Javascript
JS动态显示倒计时效果
2019/12/12 Javascript
[00:34]TI7不朽珍藏III——纯金地穴编织者饰品展示
2017/07/15 DOTA
简单实现python收发邮件功能
2018/01/05 Python
python 字典中取值的两种方法小结
2018/08/02 Python
对python 匹配字符串开头和结尾的方法详解
2018/10/27 Python
对PyQt5中的菜单栏和工具栏实例详解
2019/06/20 Python
python基于gevent实现并发下载器代码实例
2019/11/01 Python
解决django 向mysql中写入中文字符出错的问题
2020/05/18 Python
解决Keras 中加入lambda层无法正常载入模型问题
2020/06/16 Python
波比布朗英国官网:Bobbi Brown英国
2017/11/13 全球购物
Hoka One One法国官网:美国专业跑鞋品牌
2018/12/29 全球购物
一个SQL面试题
2014/08/21 面试题
电大物流学生的自我评价
2013/10/25 职场文书
预备党员党校学习自我评价分享
2013/11/12 职场文书
简短大学毕业感言
2014/01/18 职场文书
职业培训师职业生涯规划
2014/02/18 职场文书
美容院店长岗位职责
2014/04/08 职场文书
大学竞选班长演讲稿
2014/04/24 职场文书
优秀员工推荐信
2014/05/10 职场文书
企业宣传策划方案
2014/05/29 职场文书
初中家长评语大全
2014/12/26 职场文书
总经理助理岗位职责范本
2015/03/31 职场文书
被委托人身份证明
2015/08/07 职场文书
mysql中数据库覆盖导入的几种方式总结
2022/03/25 MySQL