• 技术文章 >后端开发 >Python教程

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

    2016-06-10 15:16:57原创1046
    本文实例讲述了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('//m.sbmmt.com/m/')
    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/')
    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代码

    
    
     
      
     
    

    How To Upload a File.



    upload.html页面:

    
    
     
      
     
    

    Uploaded files


    This is a list of the files you just uploaded, click on them to load/download them
      {% for file in filenames %}
    • {{file}}
    • {% endfor %}

    Code to manage a Upload


    @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)
    

    希望本文所述对大家的Python程序设计有所帮助。

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    上一篇:python判断字符串是否包含子字符串的方法 下一篇:python中django框架通过正则搜索页面上email地址的方法
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• 归纳总结Python函数进阶的使用方法• Python接口自动化测试必备基础之http协议详解• Python 3.11中的最佳新功能和功能修复• 实例详解Python面向对象的四大特征• Python数据分析之concat与merge函数(实例详解)
    1/1

    PHP中文网