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里隐藏的“禅”
Jun 16 Python
Python 两个列表的差集、并集和交集实现代码
Sep 21 Python
利用Python开发实现简单的记事本
Nov 15 Python
python图书管理系统
Apr 05 Python
python3 图片referer防盗链的实现方法
Mar 12 Python
tensorflow实现简单的卷积神经网络
May 24 Python
Django管理员账号和密码忘记的完美解决方法
Dec 06 Python
python批量创建指定名称的文件夹
Mar 21 Python
详解Python odoo中嵌入html简单的分页功能
May 29 Python
Python Web版语音合成实例详解
Jul 16 Python
Python Numpy数组扩展repeat和tile使用实例解析
Dec 09 Python
Python游戏开发实例之graphics实现AI五子棋
Nov 01 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读取XML值的代码(推荐)
2011/01/01 PHP
ThinkPHP3.1新特性之字段合法性检测详解
2014/06/19 PHP
PHP使用正则表达式实现过滤非法字符串功能示例
2018/06/04 PHP
ajax无刷新动态调用股票信息(改良版)
2008/11/01 Javascript
引入autocomplete组件时JS报未结束字符串常量错误
2014/03/19 Javascript
使用angular写一个hello world
2015/01/23 Javascript
javascript中基本类型和引用类型的区别分析
2015/05/12 Javascript
使用ngView配合AngularJS应用实现动画效果的方法
2015/06/19 Javascript
谈谈我对JavaScript中typeof和instanceof的深入理解
2015/12/25 Javascript
js 求时间差的实现代码
2016/04/26 Javascript
Angular实现跨域(搜索框的下拉列表)
2017/02/16 Javascript
jQuery完成表单验证的实例代码(纯代码)
2017/09/30 jQuery
vue实现日历表格(element-ui)
2020/09/24 Javascript
antd的select下拉框因为数据量太大造成卡顿的解决方式
2020/10/31 Javascript
JS实现购物车基本功能
2020/11/08 Javascript
使用原生javascript开发计算器实例代码
2021/02/21 Javascript
在Mac下使用python实现简单的目录树展示方法
2018/11/01 Python
对python中list的拷贝与numpy的array的拷贝详解
2019/01/29 Python
Python将json文件写入ES数据库的方法
2019/04/10 Python
pycharm new project变成灰色的解决方法
2019/06/27 Python
Keras搭建自编码器操作
2020/07/03 Python
纯css3制作网站后台管理面板
2014/12/30 HTML / CSS
HTML5 CSS3打造相册效果附源码下载
2014/06/16 HTML / CSS
wordpress添加Html5的表单验证required方法小结
2020/08/18 HTML / CSS
Lulu Guinness露露·吉尼斯官网:红唇包
2019/02/03 全球购物
服务行业口号
2014/06/11 职场文书
党员志愿者活动方案
2014/08/28 职场文书
2014年语文教学工作总结
2014/12/17 职场文书
先进班组材料范文
2014/12/25 职场文书
医务人员医德考评自我评价
2015/03/03 职场文书
清洁工个人工作总结
2015/03/05 职场文书
讲座通知范文
2015/04/23 职场文书
三八妇女节主持词
2015/07/04 职场文书
物业保洁员管理制度
2015/08/05 职场文书
Spring依赖注入多种类型数据的示例代码
2022/03/31 Java/Android
Kubernetes控制节点的部署
2022/04/01 Servers