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 cookielib 登录人人网的实现代码
Dec 19 Python
Python实现遍历windows所有窗口并输出窗口标题的方法
Mar 13 Python
Python使用scrapy采集时伪装成HTTP/1.1的方法
Apr 08 Python
Python中的XML库4Suite Server的介绍
Apr 14 Python
Python中用max()方法求最大值的介绍
May 15 Python
利用Python yagmail三行代码实现发送邮件
May 11 Python
flask框架实现连接sqlite3数据库的方法分析
Jul 16 Python
Python错误处理操作示例
Jul 18 Python
Python pandas实现excel工作表合并功能详解
Aug 29 Python
python psutil监控进程实例
Dec 17 Python
pandas factorize实现将字符串特征转化为数字特征
Dec 19 Python
python用700行代码实现http客户端
Jan 14 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
div li的多行多列 无刷新分页示例代码
2013/10/16 PHP
PHP中ini_set和ini_get函数的用法小结
2014/02/18 PHP
php利用事务处理转账问题
2015/04/22 PHP
PHP获取不了React Native Fecth参数的解决办法
2016/08/26 PHP
PHP内置加密函数详解
2016/11/20 PHP
php curl优化下载微信头像的方法总结
2018/09/07 PHP
javascript动态添加样式(行内式/嵌入式/外链式等规则)
2013/06/24 Javascript
javascript中的变量作用域以及变量提升详细介绍
2013/10/24 Javascript
在其他地方你学不到的jQuery小贴士和技巧(欢迎收藏)
2016/01/20 Javascript
Web前端开发工具——bower依赖包管理工具
2016/03/29 Javascript
jQuery通用的全局遍历方法$.each()用法实例
2016/07/04 Javascript
AngularJS 工作原理详解
2016/08/18 Javascript
用AngularJS的指令实现tabs切换效果
2016/08/31 Javascript
Angularjs 实现分页功能及示例代码
2016/09/14 Javascript
Javascript 实现简单计算器实例代码
2016/10/23 Javascript
jquery+css实现简单的图片轮播效果
2017/08/07 jQuery
详解Angular5 服务端渲染实战
2018/01/04 Javascript
解决vue打包之后静态资源图片失效的问题
2018/02/21 Javascript
详解在Vue中使用TypeScript的一些思考(实践)
2018/07/06 Javascript
vue-image-crop基于Vue的移动端图片裁剪组件示例
2018/08/28 Javascript
Node.js net模块功能及事件监听用法分析
2019/01/05 Javascript
[12:51]71泪洒现场!是DOTA2让经典重现
2014/03/24 DOTA
python的pdb调试命令的命令整理及实例
2017/07/12 Python
python re模块findall()函数实例解析
2018/01/19 Python
树莓派采用socket方式文件传输(python)
2019/06/22 Python
Python3 使用pillow库生成随机验证码
2019/08/26 Python
Python环境Pillow( PIL )图像处理工具使用解析
2019/09/12 Python
Python面向对象魔法方法和单例模块代码实例
2020/03/25 Python
Python如何重新加载模块
2020/07/29 Python
python 写一个性能测试工具(一)
2020/10/24 Python
工地例会施工汇报材料
2014/08/22 职场文书
借款协议书
2014/09/16 职场文书
群众路线自查报告及整改措施
2014/11/04 职场文书
2014年房地产销售工作总结
2014/12/01 职场文书
高中班主任评语
2014/12/30 职场文书
学习经验交流会策划书
2015/11/02 职场文书