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列表操作使用示例分享
Feb 21 Python
python使用cStringIO实现临时内存文件访问的方法
Mar 26 Python
Python3读取文件常用方法实例分析
May 22 Python
Python中static相关知识小结
Jan 02 Python
Python图像处理之图像的读取、显示与保存操作【测试可用】
Jan 04 Python
python 并发编程 多路复用IO模型详解
Aug 20 Python
Python3 文章标题关键字提取的例子
Aug 26 Python
python 中的[:-1]和[::-1]的具体使用
Feb 13 Python
在django中实现choices字段获取对应字段值
Jul 12 Python
python安装cx_Oracle和wxPython的方法
Sep 14 Python
Python 转移文件至云对象存储的方法
Feb 07 Python
Python中的np.argmin()和np.argmax()函数用法
Jun 02 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
ThinkPHP调用百度翻译类实现在线翻译
2014/06/26 PHP
ThinkPHP采用原生query实现关联查询left join实例
2014/12/02 PHP
教您去掉ie网页加载进度条的方法
2010/12/09 Javascript
jQuery 名称冲突的解决方法
2011/04/08 Javascript
JavaScript高级程序设计(第3版)学习笔记12 js正则表达式
2012/10/11 Javascript
HTML页面滚动时获取离页面顶部的距离2种实现方法
2013/09/05 Javascript
AngularJS操作键值对象类似java的hashmap(填坑小结)
2016/11/12 Javascript
JavaScript 字符串常用操作小结(非常实用)
2016/11/30 Javascript
jQuery实现判断控件是否显示的方法
2017/01/11 Javascript
jQuery实现可兼容IE6的滚动监听功能
2017/09/20 jQuery
jquery实现回车键触发事件(实例讲解)
2017/11/21 jQuery
使用element-ui table expand展开行实现手风琴效果
2019/03/15 Javascript
js继承的这6种方式!(上)
2019/04/23 Javascript
vue路由中前进后退的一些事儿
2019/05/18 Javascript
JQuery实现ul中添加LI和删除指定的Li元素功能完整示例
2019/10/16 jQuery
举例讲解Python中的身份运算符的使用方法
2015/10/13 Python
Python字符编码判断方法分析
2016/07/01 Python
Python实现随机选择元素功能
2017/09/14 Python
Django中redis的使用方法(包括安装、配置、启动)
2018/02/21 Python
删除DataFrame中值全为NaN或者包含有NaN的列或行方法
2018/11/06 Python
python获取Pandas列名的几种方法
2019/08/07 Python
详解python路径拼接os.path.join()函数的用法
2019/10/09 Python
python3 sleep 延时秒 毫秒实例
2020/05/04 Python
在canvas上实现元素图片镜像翻转动画效果的方法
2018/03/20 HTML / CSS
全球最大的跑步用品商店:Road Runner Sports
2016/09/11 全球购物
Charles & Keith欧盟:新加坡时尚品牌
2019/08/01 全球购物
门卫工作岗位职责
2013/12/17 职场文书
简短大学毕业感言
2014/01/18 职场文书
2014年党支部承诺书
2014/05/30 职场文书
2014领导班子“四风问题”对照检查材料思想汇报(执法局)
2014/09/21 职场文书
离婚协议书怎么写
2015/01/26 职场文书
七年级英语教学反思
2016/02/15 职场文书
2016年大学光棍节活动总结
2016/04/05 职场文书
2016年青少年禁毒宣传教育活动总结(学校)
2016/04/05 职场文书
2019年大学毕业生个人自我鉴定范文大全
2019/03/21 职场文书
Prometheus 监控MySQL使用grafana展示
2021/08/30 MySQL