diff --git a/.gitignore b/.gitignore index 8acba70f..d43924b6 100644 --- a/.gitignore +++ b/.gitignore @@ -118,3 +118,5 @@ demos/form/uploads/* !demos/form/uploads/.gitkeep examples/album/uploads/* !examples/album/uploads/.gitkeep +examples/ckeditor/uploads/* +!examples/ckeditor/uploads/.gitkeep diff --git a/examples/ckeditor/app.py b/examples/ckeditor/app.py index 69c4e8b8..24496372 100644 --- a/examples/ckeditor/app.py +++ b/examples/ckeditor/app.py @@ -1,7 +1,9 @@ import os +import uuid +from pathlib import Path -from flask_ckeditor import CKEditor -from flask import Flask, render_template, flash +from flask_ckeditor import CKEditor, upload_success, upload_fail +from flask import Flask, render_template, flash, request, url_for, send_from_directory from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired, Length @@ -10,8 +12,18 @@ app = Flask(__name__) app.secret_key = os.getenv('SECRET_KEY', 'secret string') +app.config['CKEDITOR_FILE_UPLOADER'] = 'upload_image' +app.config['UPLOAD_PATH'] = Path(app.root_path) / 'uploads' + ckeditor = CKEditor(app) + +class ArticleForm(FlaskForm): + title = StringField('Title', validators=[DataRequired(), Length(1, 50)]) + body = CKEditorField('Body', validators=[DataRequired()]) + submit = SubmitField('Publish') + + def clean_html(html): allowed_tags = ['a', 'abbr', 'b', 'br', 'blockquote', 'code', 'del', 'div', 'em', 'img', 'p', 'pre', 'strong', @@ -20,10 +32,15 @@ def clean_html(html): return clean(html, tags=allowed_tags, attributes=allowed_attributes) -class ArticleForm(FlaskForm): - title = StringField('Title', validators=[DataRequired(), Length(1, 50)]) - body = CKEditorField('Body', validators=[DataRequired()]) - submit = SubmitField('Publish') +def allowed_file(filename): + extension = Path(filename).suffix.lower() + return '.' in filename and extension in ['.jpg', '.gif', '.png', '.jpeg'] + + +def random_filename(old_filename): + ext = Path(old_filename).suffix + new_filename = uuid.uuid4().hex + ext + return new_filename @app.route('/', methods=['GET', 'POST']) @@ -35,3 +52,20 @@ def index(): flash('Your article is published!') return render_template('article.html', title=title, body=body) return render_template('index.html', form=form) + + +@app.route('/uploads/') +def get_image(filename): + return send_from_directory(app.config['UPLOAD_PATH'], filename) + + +@app.route('/upload', methods=['POST']) +def upload_image(): + f = request.files.get('upload') + if not allowed_file(f.filename): + return upload_fail('Image only!') + filename = random_filename(f.filename) + f.save(app.config['UPLOAD_PATH'] / filename) + image_url = url_for('get_image', filename=filename) + return upload_success(image_url, filename) + \ No newline at end of file diff --git a/examples/ckeditor/uploads/.gitkeep b/examples/ckeditor/uploads/.gitkeep new file mode 100644 index 00000000..e69de29b