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

 更新时间:2015年03月21日 15:37:18   作者:niuniu  
这篇文章主要介绍了Python使用Flask框架同时上传多个文件的方法,实例分析了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程序设计有所帮助。

相关文章

  • Python操作MongoDB详解及实例

    Python操作MongoDB详解及实例

    这篇文章主要介绍了Python操作MongoDB详解及实例的相关资料,需要的朋友可以参考下
    2017-05-05
  • 对Python新手编程过程中如何规避一些常见问题的建议

    对Python新手编程过程中如何规避一些常见问题的建议

    这篇文章中作者对Python新手编程过程中如何规避一些常见问题给出了建议,主要着眼于初学者对于一些常用函数方法在平时的使用习惯中的问题给出建议,需要的朋友可以参考下
    2015-04-04
  • Python结合多线程与协程实现高效异步请求处理

    Python结合多线程与协程实现高效异步请求处理

    在现代Web开发和数据处理中,高效处理HTTP请求是关键挑战之一,本文将结合Python异步IO(asyncio)和多线程技术,探讨如何优化请求处理逻辑,解决常见的线程事件循环问题,有需要的小伙伴可以根据需求进行选择
    2025-04-04
  • Python中的 No Module named ***问题及解决

    Python中的 No Module named ***问题及解决

    这篇文章主要介绍了Python中的 No Module named ***问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • python 把列表转化为字符串的方法

    python 把列表转化为字符串的方法

    今天小编就为大家分享一篇python 把列表转化为字符串的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • Python使用遗传算法解决最大流问题

    Python使用遗传算法解决最大流问题

    这篇文章主要为大家详细介绍了Python使用遗传算法解决最大流问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-01-01
  • Python中存取文件的4种不同操作

    Python中存取文件的4种不同操作

    这篇文章主要给大家介绍了关于Python中存取文件的4种不同操作的相关资料,分别包括Python内置方法、numpy模块方法、os模块方法以及csv模块方法,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2018-07-07
  • python3的url编码和解码,自定义gbk、utf-8的例子

    python3的url编码和解码,自定义gbk、utf-8的例子

    今天小编就为大家分享一篇python3的url编码和解码,自定义gbk、utf-8的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-08-08
  • Python基础教程之浅拷贝和深拷贝实例详解

    Python基础教程之浅拷贝和深拷贝实例详解

    这篇文章主要介绍了Python基础教程之浅拷贝和深拷贝实例详解的相关资料,需要的朋友可以参考下
    2017-07-07
  • OpenCV黑帽运算(BLACKHAT)的使用

    OpenCV黑帽运算(BLACKHAT)的使用

    本文主要介绍了OpenCV黑帽运算(BLACKHAT)的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08

最新评论