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批量提交沙箱问题实例
Oct 08 Python
用Python实现web端用户登录和注册功能的教程
Apr 30 Python
浅谈python中的变量默认是什么类型
Sep 11 Python
利用python模拟sql语句对员工表格进行增删改查
Jul 05 Python
15行Python代码带你轻松理解令牌桶算法
Mar 21 Python
python 列表递归求和、计数、求最大元素的实例
Nov 28 Python
Django使用AJAX调用自己写的API接口的方法
Mar 06 Python
Python实现微信消息防撤回功能的实例代码
Apr 29 Python
如何使用Flask-Migrate拓展数据库表结构
Jul 24 Python
Django 在iframe里跳转顶层url的例子
Aug 21 Python
python 两个一样的字符串用==结果为false问题的解决
Mar 12 Python
浅谈python 调用open()打开文件时路径出错的原因
Jun 05 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生成略缩图代码
2012/07/16 PHP
浅析PHP递归函数返回值使用方法
2013/02/18 PHP
php遍历文件夹和文件列表示例分享
2014/03/11 PHP
js 获取和设置css3 属性值的实现方法
2013/05/06 Javascript
JQuery 实现在同一页面锚点链接之间的平滑滚动
2014/10/29 Javascript
使用cluster 将自己的Node服务器扩展为多线程服务器
2014/11/10 Javascript
jQuery关键词说明插件cluetip使用指南
2015/04/21 Javascript
跟我学习javascript的prototype原型和原型链
2015/11/18 Javascript
JavaScript获取当前运行脚本文件所在目录的方法
2016/02/03 Javascript
JS实现刷新父页面不弹出提示框的方法
2016/06/22 Javascript
xcode中获取js文件的路径方法(推荐)
2016/11/05 Javascript
javascript实现复选框全选或反选
2017/02/04 Javascript
Web纯前端“旭日图”实现元素周期表
2017/03/10 Javascript
Angular 2父子组件数据传递之@Input和@Output详解 (上)
2017/07/05 Javascript
laydate 显示结束时间不小于开始时间的实例
2017/08/11 Javascript
nuxt+axios解决前后端分离SSR的示例代码
2017/10/24 Javascript
jQuery实现基本动画效果的方法详解
2018/09/06 jQuery
jQuery控制input只能输入数字和两位小数的方法
2019/05/16 jQuery
[47:39]2018DOTA2亚洲邀请赛 3.31 小组赛 A组 LGD vs OPTIC
2018/03/31 DOTA
对Pandas MultiIndex(多重索引)详解
2018/11/16 Python
Python 多维List创建的问题小结
2019/01/18 Python
python f-string式格式化听语音流程讲解
2019/06/18 Python
Python使用sklearn库实现的各种分类算法简单应用小结
2019/07/04 Python
tensorflow 变长序列存储实例
2020/01/20 Python
Keras—embedding嵌入层的用法详解
2020/06/10 Python
django项目中使用云片网发送短信验证码的实现
2021/01/19 Python
Hotels.com泰国:酒店预订网站
2019/11/20 全球购物
Ibatis中如何提高SQL Map的性能
2013/05/11 面试题
英语道歉信范文
2014/01/09 职场文书
毕业晚会主持词
2014/03/24 职场文书
机电一体化毕业生自荐信
2014/06/19 职场文书
安全生产知识竞赛活动总结
2014/07/07 职场文书
争先创优公开承诺书
2014/08/30 职场文书
酒会开场白大全
2015/06/01 职场文书
幼儿园中班班级总结
2015/08/10 职场文书
Oracle中日期的使用方法实例
2022/07/07 Oracle