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开发之thread线程基础实例入门
Nov 11 Python
Python创建对称矩阵的方法示例【基于numpy模块】
Oct 12 Python
python2.x实现人民币转大写人民币
Jun 20 Python
浅谈Python traceback的优雅处理
Aug 31 Python
python爬虫 urllib模块url编码处理详解
Aug 20 Python
用python写测试数据文件过程解析
Sep 25 Python
python实现猜数字游戏
Mar 25 Python
python实现两个一维列表合并成一个二维列表
Dec 02 Python
在python里使用await关键字来等另外一个协程的实例
May 04 Python
详解pycharm配置python解释器的问题
Oct 15 Python
使用Python实现音频双通道分离
Dec 25 Python
pycharm配置安装autopep8自动规范代码的实现
Mar 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
mysql时区问题
2008/03/26 PHP
万能的php分页类
2017/07/06 PHP
PHP设计模式(三)建造者模式Builder实例详解【创建型】
2020/05/02 PHP
用JavaScript页面不刷新时全选择,全删除(GridView)
2009/04/14 Javascript
ExtJS4利根据登录后不同的角色分配不同的树形菜单
2014/05/02 Javascript
javascript中hasOwnProperty() 方法使用指南
2015/03/09 Javascript
javascript结合Canvas 实现简易的圆形时钟
2015/03/11 Javascript
jQuery自定义动画函数实例详解(附demo源码)
2015/12/10 Javascript
JavaScript中字符串与Unicode编码互相转换的实现方法
2015/12/18 Javascript
javascript动态添加checkbox复选框的方法
2015/12/23 Javascript
带有定位当前位置的百度地图前端web api实例代码
2016/06/21 Javascript
JS定时检测任务任务完成后执行下一步的解决办法
2016/12/22 Javascript
jQuery实现动态生成表格并为行绑定单击变色动作的方法
2017/04/17 jQuery
利用vueJs实现图片轮播实例代码
2017/06/03 Javascript
jQuery模拟爆炸倒计时功能实例代码
2017/08/21 jQuery
JS继承与闭包及JS实现继承的三种方式
2017/10/15 Javascript
Vue.js划分组件的方法
2017/10/29 Javascript
详解如何在angular2中获取节点
2017/11/23 Javascript
vue cli2.0单页面title修改方法
2018/06/07 Javascript
JS实现的A*寻路算法详解
2018/12/14 Javascript
解读Python中degrees()方法的使用
2015/05/18 Python
Python+Wordpress制作小说站
2017/04/14 Python
python3写爬取B站视频弹幕功能
2017/12/22 Python
pycharm配置pyqt5-tools开发环境的方法步骤
2019/02/11 Python
Django文件存储 默认存储系统解析
2019/08/02 Python
Django权限设置及验证方式
2020/05/13 Python
什么是就业协议书
2014/04/17 职场文书
投标保密承诺书
2014/05/19 职场文书
2014财务年终工作总结
2014/12/08 职场文书
停课通知书
2015/04/24 职场文书
工程合作意向书范本
2015/05/09 职场文书
黑白记忆观后感
2015/06/18 职场文书
优秀党员主要事迹材料
2015/11/04 职场文书
如何在pycharm中快捷安装pip命令(如pygame)
2021/05/31 Python
Redis可视化客户端小结
2021/06/10 Redis
Python利用FlashText算法实现替换字符串
2022/03/31 Python