Last active
August 31, 2018 08:58
-
-
Save ts25504/a9921cfc67c4e92bf569 to your computer and use it in GitHub Desktop.
Add CKEditor upload images in Flask.
This file contains 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
def gen_rnd_filename(): | |
filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S') | |
return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000))) | |
@main.route('/ckupload/', methods=['POST', 'OPTIONS']) | |
def ckupload(): | |
"""CKEditor file upload""" | |
error = '' | |
url = '' | |
callback = request.args.get("CKEditorFuncNum") | |
if request.method == 'POST' and 'upload' in request.files: | |
fileobj = request.files['upload'] | |
fname, fext = os.path.splitext(fileobj.filename) | |
rnd_name = '%s%s' % (gen_rnd_filename(), fext) | |
filepath = os.path.join(current_app.static_folder, 'upload', rnd_name) | |
dirname = os.path.dirname(filepath) | |
if not os.path.exists(dirname): | |
try: | |
os.makedirs(dirname) | |
except: | |
error = 'ERROR_CREATE_DIR' | |
elif not os.access(dirname, os.W_OK): | |
error = 'ERROR_DIR_NOT_WRITEABLE' | |
if not error: | |
fileobj.save(filepath) | |
url = url_for('static', filename='%s/%s' % ('upload', rnd_name)) | |
else: | |
error = 'post error' | |
res = """<script type="text/javascript"> | |
window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s'); | |
</script>""" % (callback, url, error) | |
response = make_response(res) | |
response.headers["Content-Type"] = "text/html" | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you please let me know what the next step is after clicking run.py? Actually, I don't know how to upload image. Thanks.