Skip to content

Instantly share code, notes, and snippets.

@ts25504
Last active August 31, 2018 08:58
Show Gist options
  • Save ts25504/a9921cfc67c4e92bf569 to your computer and use it in GitHub Desktop.
Save ts25504/a9921cfc67c4e92bf569 to your computer and use it in GitHub Desktop.
Add CKEditor upload images in Flask.
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
@ywang04
Copy link

ywang04 commented Aug 23, 2016

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.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment