当前位置: 首页 > 编程笔记 >

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

谷梁镜
2023-03-14
本文向大家介绍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程序设计有所帮助。

 类似资料:
  • 问题内容: 有没有办法用Flask接收多个上传的文件?我尝试了以下方法: 然后打印内容 如果我上传多个文件,它将仅打印该集中的第一个文件: 是否可以使用Flask的内置上传处理方式接收多个文件?谢谢你的帮助! 问题答案: 你可以使用flask.request.files的方法getlist,例如:

  • 问题内容: 这是我上传多个文件的代码: HTML代码: 密码: 但是它会上传单个文件,而不是多个文件。 问题答案: 在模板中,你需要在上传输入中添加属性: 然后在查看功能中,上传的文件可以通过列表获取。循环此列表并在每个项目上调用save()方法将它们保存在给定路径中: 此外,你可能需要使用secure_filename()来清洁文件名: 你也可以使用此方法生成随机文件名。 完整演示 视图: im

  • 有没有办法用Flask接收多个上传的文件?我尝试了以下方法: 然后打印的内容: 如果我上载多个文件,它只打印集合中的第一个文件: 有没有一种方法可以使用Flask的内置上传处理来接收多个文件?谢谢你的帮助!

  • 使用Django REST框架的通用,我创建了一个我认为应该能够通过POST请求上传照片的终端。 到目前为止,我尝试使用Android和curl将文件发布到此endpoint,并观察到相同的行为:创建了一条新记录,但没有附加该文件。因为该文件是必填字段,服务器然后返回500错误。 这个问题看起来很相似,但是他没有使用REST框架的通用视图,我不知道为什么...我想在适当的时候利用它们。 这是我的D

  • 问题内容: 在Django rest框架中,我可以使用danialfarid / ng-file- upload 上传单个文件 views.py: serializers.py: models.py: 当我尝试上传多个文件时。我进去 chrome开发人员工具:请求有效负载 响应: 我不知道如何编写用于上传多个文件的序列化程序。任何身体都请帮忙。 提前致谢 问题答案: 我设法解决了这个问题,希望对社

  • 本文向大家介绍Laravel框架实现文件上传的方法分析,包括了Laravel框架实现文件上传的方法分析的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Laravel框架实现文件上传的方法。分享给大家供大家参考,具体如下: 配置文件: config/filesystems.php, 新建存储空间 视图中: 头像: 控制器: 更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Lara