Last active
May 16, 2022 12:58
-
-
Save greyli/81d7e5ae6c9baf7f6cdfbf64e8a7c037 to your computer and use it in GitHub Desktop.
Photo upload demo with Flask-Uploads and Flask-WTF.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- create a folder named templates, put this file into it --> | |
<!DOCTYPE html> | |
<title>Upload File</title> | |
<h1>Photo Upload</h1> | |
<form method="POST" enctype="multipart/form-data"> | |
{{ form.hidden_tag() }} | |
{{ form.photo }} | |
{% for error in form.photo.errors %} | |
<span style="color: red;">{{ error }}</span> | |
{% endfor %} | |
{{ form.submit }} | |
</form> | |
{% if file_url %} | |
<br> | |
<img src="{{ file_url }}"> | |
{% endif %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os | |
from flask import Flask, render_template | |
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class | |
from flask_wtf import FlaskForm | |
from flask_wtf.file import FileField, FileRequired, FileAllowed | |
from wtforms import SubmitField | |
basedir = os.path.abspath(os.path.dirname(__file__)) | |
app = Flask(__name__) | |
app.config['SECRET_KEY'] = 'I have a dream' | |
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(basedir, 'uploads') # you'll need to create a folder named uploads | |
photos = UploadSet('photos', IMAGES) | |
configure_uploads(app, photos) | |
patch_request_class(app) # set maximum file size, default is 16MB | |
class UploadForm(FlaskForm): | |
photo = FileField(validators=[FileAllowed(photos, 'Image only!'), FileRequired('File was empty!')]) | |
submit = SubmitField('Upload') | |
@app.route('/', methods=['GET', 'POST']) | |
def upload_file(): | |
form = UploadForm() | |
if form.validate_on_submit(): | |
filename = photos.save(form.photo.data) | |
file_url = photos.url(filename) | |
else: | |
file_url = None | |
return render_template('index.html', form=form, file_url=file_url) | |
if __name__ == '__main__': | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does
IMAGES
support video format too?@StarORC