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多线程同步Lock、RLock、Semaphore、Event实例
Nov 21 Python
python中Switch/Case实现的示例代码
Nov 09 Python
python机器学习之决策树分类详解
Dec 20 Python
利用Tkinter(python3.6)实现一个简单计算器
Dec 21 Python
pycharm+django创建一个搜索网页实例代码
Jan 24 Python
pandas 使用apply同时处理两列数据的方法
Apr 20 Python
Python过滤txt文件内重复内容的方法
Oct 21 Python
在Python中将函数作为另一个函数的参数传入并调用的方法
Jan 22 Python
tensorflow对图像进行拼接的例子
Feb 05 Python
学python爬虫能做什么
Jul 29 Python
如何真正的了解python装饰器
Aug 14 Python
利用python进行数据加载
Jun 20 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 - Html Transfer Code
2006/10/09 PHP
php-perl哈希算法实现(times33哈希算法)
2013/12/30 PHP
php倒计时出现-0情况的解决方法
2016/07/28 PHP
Laravel框架实现定时发布任务的方法
2018/08/16 PHP
php中的buffer缓冲区用法分析
2019/05/31 PHP
用javascript编写的第一人称射击游戏
2007/02/25 Javascript
jquery插件之easing 动态菜单
2010/08/21 Javascript
jQuery 网易相册鼠标移动显示隐藏效果实现代码
2013/03/31 Javascript
nodejs中使用monk访问mongodb
2014/07/06 NodeJs
EasyUi datagrid 实现表格分页
2015/02/10 Javascript
JavaScript 动态加载脚本和样式的方法
2015/04/13 Javascript
浅谈Jquery核心函数
2015/06/18 Javascript
JavaScript中innerHTML,innerText,outerHTML的用法及区别
2015/09/01 Javascript
jQuery解析与处理服务器端返回xml格式数据的方法详解
2016/07/04 Javascript
JavaScript大数相加相乘的实现方法实例
2020/10/18 Javascript
Python urlopen 使用小示例
2008/09/06 Python
Python下的Softmax回归函数的实现方法(推荐)
2017/01/26 Python
详解Pytorch 使用Pytorch拟合多项式(多项式回归)
2018/05/24 Python
python寻找list中最大值、最小值并返回其所在位置的方法
2018/06/27 Python
Python Web编程之WSGI协议简介
2018/07/18 Python
python调用staf自动化框架的方法
2018/12/26 Python
Python搭建HTTP服务过程图解
2019/12/14 Python
Python爬虫爬取电影票房数据及图表展示操作示例
2020/03/27 Python
Pytorch框架实现mnist手写库识别(与tensorflow对比)
2020/07/20 Python
python之pygame模块实现飞机大战完整代码
2020/11/29 Python
canvas粒子动画背景的实现示例
2018/09/03 HTML / CSS
html5给汉字加拼音加进度条的实现代码
2020/04/07 HTML / CSS
美国一家主打母婴用品的团购网站:zulily
2017/09/19 全球购物
我能否用void** 指针作为参数, 使函数按引用接受一般指针
2013/02/16 面试题
利用promise及参数解构封装ajax请求的方法
2021/03/24 Javascript
股权收购意向书
2014/04/01 职场文书
正科级干部考察材料
2014/05/29 职场文书
化工实习心得体会
2014/09/09 职场文书
百日宴上的祝酒词
2015/08/10 职场文书
python 安全地删除列表元素的方法
2022/03/16 Python
python playwrigh框架入门安装使用
2022/07/23 Python