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 17 Python
闭包在python中的应用之translate和maketrans用法详解
Aug 27 Python
python进阶教程之动态类型详解
Aug 30 Python
python 中split 和 strip的实例详解
Jul 12 Python
spyder常用快捷键(分享)
Jul 19 Python
Python实现字典按照value进行排序的方法分析
Dec 23 Python
Pyspider中给爬虫伪造随机请求头的实例
May 07 Python
python3中的md5加密实例
May 29 Python
python 不同方式读取文件速度不同的实例
Nov 09 Python
python进程和线程用法知识点总结
May 28 Python
Python Handler处理器和自定义Opener原理详解
Mar 05 Python
基于OpenCV的网络实时视频流传输的实现
Nov 15 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代码网站如何防范SQL注入漏洞攻击建议分享
2012/03/01 PHP
通过缓存数据库结果提高PHP性能的原理介绍
2012/09/05 PHP
ThinkPHP惯例配置文件详解
2014/07/14 PHP
php遍历删除整个目录及文件的方法
2015/03/13 PHP
分享十款最出色的PHP安全开发库中文详细介绍
2015/03/22 PHP
PHP异常类及异常处理操作实例详解
2018/12/19 PHP
Extjs入门之动态加载树代码
2010/04/09 Javascript
使用upstart把nodejs应用封装为系统服务实例
2014/06/01 NodeJs
node.js中的buffer.slice方法使用说明
2014/12/10 Javascript
js基于面向对象实现网页TAB选项卡菜单效果代码
2015/09/09 Javascript
jsp 自动编译机制详细介绍
2016/12/01 Javascript
微信上传视频文件提示(推荐)
2018/11/22 Javascript
浏览器事件循环与vue nextTicket的实现
2019/04/16 Javascript
微信小程序select下拉框实现效果
2019/05/15 Javascript
解决mui框架中switch开关通过js控制开或者关状态时小圆点不动的问题
2019/09/03 Javascript
jQuery实现tab栏切换效果
2020/12/22 jQuery
[49:20]VG vs TNC Supermajor小组赛B组败者组决赛 BO3 第二场 6.2
2018/06/03 DOTA
Python探索之爬取电商售卖信息代码示例
2017/10/27 Python
tensorflow实现对图片的读取的示例代码
2018/02/12 Python
pandas获取groupby分组里最大值所在的行方法
2018/04/20 Python
Python数据可视化之画图
2019/01/15 Python
python 中值滤波,椒盐去噪,图片增强实例
2019/12/18 Python
Pytorch 多维数组运算过程的索引处理方式
2019/12/27 Python
通过Turtle库在Python中绘制一个鼠年福鼠
2020/02/03 Python
使用keras根据层名称来初始化网络
2020/05/21 Python
Python实现AES加密,解密的两种方法
2020/10/03 Python
Python将list元素转存为CSV文件的实现
2020/11/16 Python
python 监控服务器是否有人远程登录(详细思路+代码)
2020/12/18 Python
Django解决frame拒绝问题的方法
2020/12/18 Python
美国知名玩具品牌:Melissa & Doug
2016/08/16 全球购物
全球酒店比价网:HotelsCombined
2017/06/20 全球购物
英国电气世界:Electrical World
2019/09/08 全球购物
幼儿园国庆节活动方案
2014/02/01 职场文书
建设幸福中国演讲稿
2014/09/11 职场文书
趣味运动会赞词
2015/07/22 职场文书
Python基础之元编程知识总结
2021/05/23 Python