Python使用Flask框架同时上传多个文件的方法

本文实例讲述了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程序设计有所帮助。

(0)

相关推荐

  • Flask框架的学习指南之制作简单blog系统

    之前写了一篇flask开发环境搭建,今天继续,进行一个实战小项目-blog系统. blog系统很简单,只有一个页面,然后麻雀虽小五脏俱全.这里目的不是为了做项目而做项目,这篇文章本意是通过这次练习传达以下几个知识点: 1.从全局上了解flask项目的目录结构 2.flask项目的运行机制 3.flask框架实现MVC架构 4.flask-sqlalchemy 操作mysql数据库 一.新建项目:blog系统 在pycharm中,新建flask项目,如下图: 完成后的目录结构是这样的:非常简单,一

  • Python的Flask框架与数据库连接的教程

     命令行方式运行Python脚本 在这个章节中,我们将写一些简单的数据库管理脚本.在此之前让我们来复习一下如何通过命令行方式执行Python脚本. 如果Linux 或者OS X的操作系统,需要有执行脚本的权限.例如: chmod a+x script.py 该脚本有个指向使用解释器的命令行.再脚本赋予执行权限后就可以通过命令行执行,就像这样: like this: ./script.py <arguments> 然而,在Windows系统上这样做是不行的,你必须提供Python解释器作为必选参

  • Flask框架的学习指南之开发环境搭建

    Flask是一个使用 Python 编写的轻量级 Web 应用框架.其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2.很多功能的实现都参考了django框架.由于项目需要,在此记录下学习的过程及心得. 工欲善其事,必先利其器.就从搭建一套flask开发环境开始flask之旅吧. 一.平台说明 操作系统:window 7  64bit  数据库:mysql5.6  python:v2.7  开发集成软件:PyCharm5.0 二.开发环境搭建 1.安装flask框架包 1

  • Flask框架的学习指南之用户登录管理

    继续flask的学习之旅.今天介绍flask的登陆管理模块,还记得上一篇中的blog小项目么,登录是咱们自己写的验证代码,大概有以下几个步骤: 1.在登录框中输入用户名和密码 2.flask view函数获取用户密码,然后到数据库中查询该用户信息,进行匹配 3.如果成功,就写入session中,重定向到首页 4.如果对于特定视图,必须要登录才能访问,那么需要在每个视图函数验证session里是否存在该用户. 今天继续改造blog项目,介绍的flask-login模块就是替我们来搞定这些业务相关度

  • Python的Flask框架中web表单的教程

     概要 在前面章节我们为主页定义了一个简单的模板,部分尚未实现的模块如用户或帖子等使用模拟的对象作为临时占位. 本章我们将看到如何利用web表单填补这些空白. web表单是web应用中最基本的构建要素,我们将通过表单来实现用户发帖和应用登录功能. 完成本章内容你需要基于前面章节完成的微博应用代码,请确认这些代码已安装并能正常运行. 配置 Flask-WTF是WTForms项目的Flask框架扩展,我们将用他来帮助我们处理web表单. 大部分Flask扩展都需要定义相关配置项,所以我们先来在应用根

  • 30分钟搭建Python的Flask框架并在上面编写第一个应用

    Flask 是一种很赞的Python web框架.它极小,简单,最棒的是它很容易学. 今天我来带你搭建你的第一个Flask web应用!和官方教程 一样,你将搭建你自己的微博客系统:Flaskr.和官方Flask教程不同的是--我们通过使用Stormpath来创建并管理用户账户和数据,你的工作效率会更高.开发进程会显著地加快! 我们这就开始吧. 注意:这篇教程面向Flask开发新人,帮助他们理解如何使用Flask和Stormpath建立一个简单的网站.本文是Flask官方教程的改版. 目标 Fl

  • Python的Flask框架中@app.route的用法教程

    在我上一篇文章,我搭了一个框架,模拟了Flask网站上"@app.route('/')"第一条例子的行为. 如果你错过了那篇"这不是魔法",请点击这里. 在这篇文章中,我们打算稍微调高点难度,为我们的URL加入可变参数的能力,在本文的最后,我们将支持下述代码段所期望达到的行为. app = Flask(__name__) @app.route("/hello/<username>") def hello_user(username):

  • 在Linux上安装Python的Flask框架和创建第一个app实例的教程

    无论你在linux上娱乐还是工作,这对你而言都是一个使用python来编程的很好的机会.回到大学我希望他们教我的是Python而不是Java,这学起来很有趣且在实际的应用如yum包管理器中很有用. 本篇教程中我会带你使用python和一个称为flask的微型框架来构建一个简单的应用,来显示诸如每个进程的内存使用,CPU百分比之类有用的信息. 前置需求 Python基础.列表.类.函数.模块.HTML/CSS (基础). 学习这篇教程你不必是一个python高级开发者,但是首先我建议你阅读http

  • Python的Flask框架中实现简单的登录功能的教程

     回顾 在前面的系列章节中,我们创建了一个数据库并且学着用用户和邮件来填充,但是到现在我们还没能够植入到我们的程序中. 两章之前,我们已经看到怎么去创建网络表单并且留下了一个实现完全的登陆表单. 在这篇文章中,我们将基于我门所学的网络表单和数据库来构建并实现我们自己的用户登录系统.教程的最后我们小程序会实现新用户注册,登陆和退出的功能. 为了能跟上这章节,你需要前一章节最后部分,我们留下的微博程序.请确保你的程序已经正确安装和运行. 在前面的章节,我们开始配置我们将要用到的Flask扩展.为了登

  • 使用Python的Flask框架实现视频的流媒体传输

    Flask 是一个 Python 实现的 Web 开发微框架.这篇文章是一个讲述如何用它实现传送视频数据流的详细教程. 我敢肯定,现在你已经知道我在O'Reilly Media上发布了有关Flask的一本书和一些视频资料.在这些上面,Flask框架介绍的覆盖面是相当完整的,出于某种原因,也有一小部分的功能没有太多的提到,因此我认为在这里写一篇介绍它们的文章是一个好主意. 这篇文章是专门介绍流媒体的,这个有趣的功能让Flask应用拥有这样一种能力,以分割成小数据块的方式,高效地为大型请求提供数据,

  • Flask框架学习笔记(一)安装篇(windows安装与centos安装)

    Flask 依赖于两个外部库: Werkzeug  和  Jinja2  . Werkzeug 是一个 WSGI (在 web 应用和多种服务器之间开发和部署的标准 Python 接口) 的工具集,Jinja2 负责渲染模板. 一.安装 Flask安装的前提条件 1.已安装python2.x版本 2.已安装easy_install 在安装flask之前,你必须要先安装python和easy_install,easy_install只支持pyhon2.x版本不支持python3.x版本,所以你在安

随机推荐