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装饰器使用的一些建议
Jun 03 Python
Python 多线程实例详解
Mar 25 Python
在python中使用正则表达式查找可嵌套字符串组
Oct 24 Python
Python中super函数的用法
Nov 17 Python
python初学之用户登录的实现过程(实例讲解)
Dec 23 Python
Django ManyToManyField 跨越中间表查询的方法
Dec 18 Python
python Pexpect 实现输密码 scp 拷贝的方法
Jan 03 Python
python实现定时发送qq消息
Jan 18 Python
基于python实现地址和经纬度转换
May 19 Python
基于Python+QT的gui程序开发实现
Jul 03 Python
Python实现数字的格式化输出
Aug 01 Python
python数字图像处理:图像的绘制
Jun 28 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的无限分类实现想法~
2007/01/02 PHP
优化使用mysql存储session的php代码
2008/01/10 PHP
PHP Session变量不能传送到下一页的解决方法
2009/11/27 PHP
visual studio code 调试php方法(图文详解)
2017/09/15 PHP
JavaScript 联动的无限级封装类,数据采用非Ajax方式,随意添加联动
2010/06/29 Javascript
在javascript中如何得到中英文混合字符串的长度
2014/01/17 Javascript
Javascript 按位与赋值运算符 (&amp;=)使用介绍
2014/02/04 Javascript
JS计算网页停留时间代码
2014/04/28 Javascript
avalon js实现仿google plus图片多张拖动排序附源码下载
2015/09/24 Javascript
JS实现的最简Table选项卡效果
2015/10/14 Javascript
JavaScript驾驭网页-获取网页元素
2016/03/24 Javascript
jQuery 如何给Carousel插件添加新的功能
2016/04/18 Javascript
Bootstrap表单布局样式代码
2016/05/31 Javascript
extjs简介_动力节点Java学院整理
2017/07/17 Javascript
jQuery接受后台传递的List的实例详解
2017/08/02 jQuery
Vue插值、表达式、分隔符、指令知识小结
2018/10/12 Javascript
Python中给List添加元素的4种方法分享
2014/11/28 Python
python抽象基类用法实例分析
2015/06/04 Python
高效测试用例组织算法pairwise之Python实现方法
2017/07/19 Python
Python实现判断字符串中包含某个字符的判断函数示例
2018/01/08 Python
Pyqt实现无边框窗口拖动以及窗口大小改变
2018/04/19 Python
Python将list中的string批量转化成int/float的方法
2018/06/26 Python
selenium+python自动化测试环境搭建步骤
2019/06/03 Python
用python3 返回鼠标位置的实现方法(带界面)
2019/07/05 Python
Pandas聚合运算和分组运算的实现示例
2019/10/17 Python
pandas-resample按时间聚合实例
2019/12/27 Python
牵手50香港:专为黄金岁月的单身人士而设的交友网站
2020/08/14 全球购物
Weblogc domain问题
2014/01/27 面试题
华为的Java面试题
2014/03/07 面试题
中学教师管理制度
2014/01/14 职场文书
生物科学专业毕业生求职信
2014/06/02 职场文书
集中采购方案
2014/06/10 职场文书
党的群众路线教育实践活动学习笔记范文
2014/11/06 职场文书
2014年政府采购工作总结
2014/12/09 职场文书
个人党性分析总结
2015/03/05 职场文书
乡镇党建工作总结2015
2015/05/19 职场文书