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中的装饰器、闭包和functools的教程
Apr 02 Python
Python中的异常处理相关语句基础学习笔记
Jul 11 Python
python读取图片并修改格式与大小的方法
Jul 24 Python
python和mysql交互操作实例详解【基于pymysql库】
Jun 04 Python
使用Python画股票的K线图的方法步骤
Jun 28 Python
Python 图像对比度增强的几种方法(小结)
Sep 25 Python
Python中类似于jquery的pyquery库用法分析
Dec 02 Python
Python 简单计算要求形状面积的实例
Jan 18 Python
Python猜数字算法题详解
Mar 01 Python
Python基于pillow库实现生成图片水印
Sep 14 Python
python 实时调取摄像头的示例代码
Nov 25 Python
Python控制台输出俄罗斯方块的方法实例
Apr 17 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 parse_url 一个好用的函数
2009/10/03 PHP
php懒人函数 自动添加数据
2011/06/28 PHP
基于PHP 面向对象之成员方法详解
2013/05/04 PHP
php 获取SWF动画截图示例代码
2014/02/10 PHP
PHP多态代码实例
2015/06/26 PHP
无缝滚动改进版支持上下左右滚动(封装成函数)
2012/12/04 Javascript
node.js WEB开发中图片验证码的实现方法
2014/06/03 Javascript
javascript中cookie对象用法实例分析
2015/01/30 Javascript
JS和css实现检测移动设备方向的变化并判断横竖屏幕
2015/05/25 Javascript
详解JavaScript语言的基本语法要求
2015/11/20 Javascript
JavaScript获取当前cpu使用率的方法
2015/12/15 Javascript
jQuery实现可展开折叠的导航效果示例
2016/09/12 Javascript
微信小程序 scroll-view实现上拉加载与下拉刷新的实例
2017/01/21 Javascript
js仿淘宝商品放大预览功能
2017/03/15 Javascript
解决OneThink中无法异步提交kindeditor文本框中修改后的内容方法
2017/05/05 Javascript
javascript 封装Date日期类实例详解
2017/05/28 Javascript
node通过npm写一个cli命令行工具
2017/10/12 Javascript
angularjs实现table增加tr的方法
2018/02/27 Javascript
微信小程序实现tab页面切换功能
2018/07/13 Javascript
PHPStorm中如何对nodejs项目进行单元测试详解
2019/02/28 NodeJs
Nest.js 授权验证的方法示例
2021/02/22 Javascript
用Python实现一个简单的能够发送带附件的邮件程序的教程
2015/04/08 Python
归纳整理Python中的控制流语句的知识点
2015/04/14 Python
Linux下python与C++使用dlib实现人脸检测
2018/06/29 Python
python 反向输出字符串的方法
2018/07/16 Python
python celery分布式任务队列的使用详解
2019/07/08 Python
Python 日期区间处理 (本周本月上周上月...)
2019/08/08 Python
Pytorch之contiguous的用法
2019/12/31 Python
Python压缩模块zipfile实现原理及用法解析
2020/08/14 Python
pandas按条件筛选数据的实现
2021/02/20 Python
小班下学期评语
2014/05/04 职场文书
企业金融服务方案
2014/06/03 职场文书
中标通知书
2015/04/17 职场文书
工商局调档介绍信
2015/10/22 职场文书
利用Selenium添加cookie实现自动登录的示例代码(fofa)
2021/05/08 Python
nginx中proxy_pass各种用法详解
2021/11/07 Servers