7. Flask file upload

7. Flask file upload

 1.1. Upload files and access the last file

upload_file_demo.py

from flask import Flask,request,render_template
import os
from werkzeug.utils import secure_filename
from flask import send_from_directory

app = Flask(__name__)

#New images folder, UPLOAD_PATH is the path of images
UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'images')

@app.route('/upload/',methods=['GET','POST'])
def settings():
    if request.method =='GET':
        return render_template('upload.html')
    else:
        desc = request.form.get('desc')
        avatar = request.files.get('avatar')
        # Pack the file name for safety, but there is a problem with the Chinese file name display
        filename = secure_filename(avatar.filename)
        avatar.save(os.path.join(UPLOAD_PATH,filename))
        print(desc)
        return'File upload successfully'

#Access uploaded files
#Browser access: http://127.0.0.1:5000/images/django.jpg/You can view the file
@app.route('/images/<filename>/',methods=['GET','POST'])
def get_image(filename):
    return send_from_directory(UPLOAD_PATH,filename)

@app.route('/')
def hello_world():
    return'Hello World!'

if __name__ =='__main__':
    app.run(debug=True)

upload.html

<form action="" method="post" enctype="multipart/form-data">
    <table>
        <tbody>
            <tr>
                <td>Portrait:</td>
                <td><input type="file" name="avatar"></td>
            </tr>
            <tr>
                <td>Description:</td>
                <td><input type="text" name="desc"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"></td>
            </tr>
        </tbody>
    </table>
</form>

1.2. Use flask-wtf to verify uploaded files

forms.py

from wtforms import Form,FileField,StringField
from wtforms.validators import InputRequired
from flask_wtf.file import FileRequired,FileAllowed

class UploadForm(Form):
    avatar = FileField(validators=[FileRequired(), #FileRequired must be uploaded
                                   FileAllowed(['jpg','png','gif']) #FileAllowed: must be a file in the specified format
                                   ])
    desc = StringField(validators=[InputRequired()])

upload_file_demo.py

from flask import Flask, request, render_template
import os
from werkzeug.utils import secure_filename
from flask import send_from_directory
from forms import UploadForm
from werkzeug.datastructures import CombinedMultiDict

app = Flask(__name__)

# Create images folder, UPLOAD_PATH is the path of images
UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'images')


@app.route('/upload/', methods=['GET','POST'])
def settings():
    if request.method =='GET':
        return render_template('upload.html')
    else:
        # The file is obtained from request and files. Here, CombinedMultiDict is used to combine the data of form and file and verify together
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            desc = request.form.get('desc')
            avatar = request.files.get('avatar')
            # Pack the file name for safety, but there is a problem with the Chinese file name display
            filename = secure_filename(avatar.filename)
            avatar.save(os.path.join(UPLOAD_PATH, filename))
            print(desc)
            return'File upload successfully'
        else:
            print(form.errors)
            return "fail"


# Access uploaded files
# Browser access: http://127.0.0.1:5000/images/django.jpg/You can view the file
@app.route('/images/<filename>/', methods=['GET','POST'])
def get_image(filename):
    return send_from_directory(UPLOAD_PATH, filename)


@app.route('/')
def hello_world():
    return'Hello World!'


if __name__ =='__main__':
    app.run(debug=True)
Reference: https://cloud.tencent.com/developer/article/1172859 7. Flask file upload-Cloud + Community-Tencent Cloud