Skip to content

Instantly share code, notes, and snippets.

@takwas
Last active December 9, 2015 09:02
Show Gist options
  • Save takwas/5be95f928df37ad68c9e to your computer and use it in GitHub Desktop.
Save takwas/5be95f928df37ad68c9e to your computer and use it in GitHub Desktop.
Flask image uploading
class ProfileForm(Form):
img_fld = FileField('Upload a Profile Photo', \
validators=[FileAllowed(config['IMG_ALLOWED_EXTENSIONS'], 'Images only!')])
# saves an image to the filesystem based
# on the given parameters and returns two things:
# 1. True/False (if the file was successfully saved or not)
# 2. The filename used in saving the file
def save_image(img_file, upload_folder, allowed_extensions=None, img_name_prefix=None, img_name_suffix=None):
from werkzeug import secure_filename
from base_form import config
# retrieve and secure filename
img_name = img_file.filename
img_name = secure_filename(img_name)
# get image allowed extensions config from forms
allowed_extensions = config.get('IMG_ALLOWED_EXTENSIONS', ['JPG', 'JPEG', 'PNG'])
# get filename and extension
if '.' in img_name:
name_extension_split = img_name.rsplit('.', 1)
name, ext = name_extension_split[0], name_extension_split[1]
else:
return False, img_name
# ensure file format is valid
if ext not in allowed_extensions:
return False, img_name
# generate new name for image
new_name = get_random_string(n=4)
img_name = new_name
# add img_name_prefix and img_name_suffix if any
if img_name_prefix is None:
img_name_prefix = ''
if img_name_suffix is None:
img_name_suffix = ''
# join all parts of filename (including file extension)
img_name = ''.join([img_name_prefix, new_name, img_name_suffix, '.', ext])
# some file checks and ops
import os
from distutils.dir_util import mkpath, DistutilsFileError
# create upload_folder if doesn't already exist
try:
mkpath(upload_folder)
except DistutilsFileError:
print("DistutilsFileError: Couldn't create folder to store image.")
return False, img_name
# check if filename is existing
filelist = os.listdir(upload_folder)
while True:
if img_name in filelist:
name, ext = os.path.splitext(img_name)
img_name = ''.join([name, '_', get_random_string(n=3), ext])
if img_name not in filelist:
break
# finally, save image file with "img_name" to "upload_folder"
img_file.save(os.path.join(upload_folder, img_name))
print "IMAGE SAVED TO %r " %os.path.abspath(os.path.join(upload_folder, img_name)) ####DEBUG
return True, img_name
if request.method=='POST':
profile_form = ProfileForm(request.form)
# retrieve uploaded image file object from request
img_file = request.files.get('img_fld', None)
print "IMAGE FILE:: {0}".format(img_file) ####DEBUG
if img_file is not None:
# config['IMG_ALLOWED_EXTENSIONS'] is imported from forms.py
image_was_saved, img_name = utils.save_image(img_file=img_file, \
upload_folder=utils.get_profile_img_uploads_path(user=marketer), \
img_name_prefix=marketer.username)
if image_was_saved:
marketer.marketer_details.set_profile_img(img_name)
update_succeeded.append("Image uploaded successfully!")
else:
marketer.marketer_details.set_default_profile_img() # set default user profile image for user
update_failed.append("Account updated, but profile image data was not saved.")
else:
marketer.marketer_details.set_default_profile_img() # set default user profile image for user
update_failed.append("Your image failed to upload. No image provided.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment