Viết ứng dụng upload file đơn giản sử dụng Flask


  • administrators

    Flask là một ngôn ngữ nhẹ nhàng, hôm nay tôi sẽ thực hành nó để viết một ứng dụng upload file đơn giản. Các bước thực hiện như sau:

    Bước 1: Tạo thư mục templates sau đó tạo 2 file
    File index.html với nội dung như sau:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <link href="//netdna.bootstrapcdn.com/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>
    

    File upload.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <link href="//netdna.bootstrapcdn.com/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>
    

    Bước 2: Tạo thư mục lưu trữ ảnh có tên là upload
    Bước 3: Viết chương trình: tạo file
    File app.py

    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
        )
    

    File setup.py

    from setuptools import setup
     
    setup(name='multipleUpload', version='1.0',
          description='Code example demonstrating how to upload multiple files using Flask',
          author='Khanh Nguyen', author_email='khanhnn@pythonvietnam.info',
          url='http://pythonvietnam.info/',
     
          #  Uncomment one or more lines below in the install_requires section
          #  for the specific client drivers/modules your application needs.
          install_requires=['flask']
        )
    

    Chúc bạn thành công !


Hãy đăng nhập để trả lời
 

Có vẻ như bạn đã mất kết nối tới Cộng đồng Python Việt Nam, vui lòng đợi một lúc để chúng tôi thử kết nối lại.