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字符转换
Sep 06 Python
python计算程序开始到程序结束的运行时间和程序运行的CPU时间
Nov 28 Python
树莓派中python获取GY-85九轴模块信息示例
Dec 05 Python
在Windows中设置Python环境变量的实例讲解
Apr 28 Python
python使用插值法画出平滑曲线
Dec 15 Python
python统计中文字符数量的两种方法
Jan 31 Python
Python Web框架之Django框架Model基础详解
Aug 16 Python
如何使用Python脚本实现文件拷贝
Nov 20 Python
有关Tensorflow梯度下降常用的优化方法分享
Feb 04 Python
解决django框架model中外键不落实到数据库问题
May 20 Python
Anaconda使用IDLE的实现示例
Sep 23 Python
Pytest中skip和skipif的具体使用方法
Jun 30 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
simplehtmldom Doc api帮助文档
2012/03/26 PHP
php 调试利器debug_print_backtrace()
2012/07/23 PHP
PHP static局部静态变量和全局静态变量总结
2014/03/02 PHP
免费的ip数据库淘宝IP地址库简介和PHP调用实例
2014/04/08 PHP
php使用GD库创建图片缩略图的方法
2015/06/10 PHP
深入浅析PHP7.0新特征(五大新特征)
2015/10/29 PHP
JS类库Bindows1.3中的内存释放方式分析
2007/03/08 Javascript
javascript Demo模态窗口
2009/12/06 Javascript
Jquery 跨域访问 Lightswitch OData Service的方法
2013/09/11 Javascript
深入理解Javascript中this的作用域
2014/08/12 Javascript
详解JavaScript基本类型和引用类型
2015/12/09 Javascript
NodeJs——入门必看攻略
2016/06/27 NodeJs
JS 数字转换为大写金额的简单实例
2016/08/04 Javascript
微信小程序 slider 详解及实例代码
2017/01/10 Javascript
vue2滚动条加载更多数据实现代码
2017/01/10 Javascript
Angular2中select用法之设置默认值与事件详解
2017/05/07 Javascript
关于vue-router的beforeEach无限循环的问题解决
2017/09/09 Javascript
如何提升vue.js中大型数据的性能
2019/06/21 Javascript
[10:42]Team Liquid Vs Newbee
2018/06/07 DOTA
python基于Tkinter库实现简单文本编辑器实例
2015/05/05 Python
python下os模块强大的重命名方法renames详解
2017/03/07 Python
Python numpy实现二维数组和一维数组拼接的方法
2018/06/05 Python
pycharm重置设置,恢复默认设置的方法
2018/10/22 Python
python操作文件的参数整理
2019/06/11 Python
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
2019/10/06 Python
python实现飞机大战小游戏
2019/11/08 Python
python缩进长度是否统一
2020/08/02 Python
HTML5 的新的表单元素(datalist/keygen/output)使用介绍
2013/07/19 HTML / CSS
威盛公司软件C++工程师笔试题面试题
2012/07/16 面试题
客户代表自我评价范例
2013/09/24 职场文书
关于环保的建议书400字
2014/03/12 职场文书
毕业生自荐材料范文
2014/12/30 职场文书
银行稽核岗位职责
2015/04/13 职场文书
古见同学有交流障碍症 第二季宣传CM公开播出
2022/04/11 日漫
关于的python五子棋的算法
2022/05/02 Python
Redis实战之Lettuce的使用技巧详解
2022/12/24 Redis