예제 #1
0
    def upload(f, user_id):
        """Upload the new avatar.

        Checks if the file type is allowed if so removes any
        previous uploaded avatars.
        """
        filename = f.filename

        # Check if the file is allowed.
        if filename == '':
            return

        if '.' not in filename or not filename.rsplit('.', 1)[1].lower() \
                in ALLOWED_EXTENSIONS:
            flash(_('Filetype not allowed'), 'danger')
            return

        # convert the name.
        filename = 'avatar_%d.%s' % (user_id, filename.rsplit('.', 1)[1])
        path = os.path.join(os.getcwd(), UPLOAD_DIR, filename)

        # Check if avatar exists if so remove.
        filename_noext, filename_ext = FileAPI.split_name(filename)

        for file in os.listdir(UPLOAD_DIR):
            if fnmatch.fnmatch(file, filename_noext + '.*'):
                remove_path = os.path.join(os.getcwd(), UPLOAD_DIR, file)
                os.remove(remove_path)

        # Save file.
        f.save(path)
        os.chmod(path, 0o644)
        return