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 17 Python
Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
Mar 19 Python
python监控进程脚本
Apr 12 Python
对python 生成拼接xml报文的示例详解
Dec 28 Python
对python字典过滤条件的实例详解
Jan 22 Python
python binascii 进制转换实例
Jun 12 Python
python 随机生成10位数密码的实现代码
Jun 27 Python
numpy中三维数组中加入元素后的位置详解
Nov 28 Python
Pytorch DataLoader 变长数据处理方式
Jan 08 Python
聊聊Python pandas 中loc函数的使用,及跟iloc的区别说明
Mar 03 Python
python多次执行绘制条形图
Apr 20 Python
Python爬取奶茶店数据分析哪家最好喝以及性价比
Sep 23 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
电脑硬件及电脑配置知识大全
2020/03/17 数码科技
PHP实现懒加载的方法
2015/03/07 PHP
实例说明js脚本语言和php脚本语言的区别
2019/04/04 PHP
深入认识JavaScript中的函数
2007/01/22 Javascript
日期 时间js控件
2009/05/07 Javascript
javascript 一个函数对同一元素的多个事件响应
2009/07/25 Javascript
ExtJS 学习专题(一) 如何应用ExtJS(附实例)
2010/03/11 Javascript
jQuery数组处理方法汇总
2011/06/20 Javascript
ANT 压缩(去掉空格/注释)JS文件可提高js运行速度
2013/04/15 Javascript
方便实用的jQuery checkbox复选框全选功能简单实例
2013/10/09 Javascript
使用JavaScript和CSS实现文本隔行换色的方法
2015/11/04 Javascript
基于JavaScript实现TAB标签效果
2016/01/12 Javascript
微信小程序 navigation API实例详解
2016/10/02 Javascript
JS实现线性表的顺序表示方法示例【经典数据结构】
2017/04/11 Javascript
JS原型继承四步曲及原型继承图一览
2017/11/28 Javascript
深入探讨JavaScript的最基本部分之执行上下文
2019/02/12 Javascript
Webpack4 使用Babel处理ES6语法的方法示例
2019/03/07 Javascript
js中script的上下放置区别,Dom的增删改创建操作实例分析
2019/12/16 Javascript
JavaScript用document.write()输出换行的示例代码
2020/11/26 Javascript
[01:29:17]RNG vs Liquid 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.23
2019/09/05 DOTA
phpsir 开发 一个检测百度关键字网站排名的python 程序
2009/09/17 Python
python 读取txt,json和hdf5文件的实例
2018/06/05 Python
十个Python练手的实战项目,学会这些Python就基本没问题了(推荐)
2019/04/26 Python
解决flask接口返回的内容中文乱码的问题
2020/04/03 Python
python图片验证码识别最新模块muggle_ocr的示例代码
2020/07/03 Python
Python Matplotlib绘图基础知识代码解析
2020/08/31 Python
BrandAlley英国:法国折扣奢侈品网上零售商
2017/07/03 全球购物
全球速卖通俄罗斯站:AliExpress俄罗斯
2019/06/17 全球购物
教育学专业实习生的自我鉴定
2013/11/26 职场文书
韩国商务邀请函
2014/01/14 职场文书
财政专业求职信范文
2014/02/19 职场文书
领导班子整改方案和个人整改措施
2014/10/25 职场文书
大学生学期个人总结
2015/02/12 职场文书
应届毕业生的自我评价
2019/06/21 职场文书
JAVA 线程池(池化技术)的实现原理
2022/04/28 Java/Android
Python序列化模块JSON与Pickle
2022/06/05 Python