rodrigobertin
6/25/2019 - 12:18 PM

Upload simple image with Flask

Upload images with Flask

def upload_image(upload_folder, input_name='image'):
    """
    Upload images with flask
    :param upload_folder: 
    :param input_name: 
    :return: 
    """
    from werkzeug.utils import secure_filename
    import os
    import random
    from flask import request

    allowed_types = ['image/jpg', 'image/jpeg', 'image/png', 'image/svg+xml', 'image/gif']

    if not upload_folder:
        msg = u'No se especifico carpeta de subida'
        print(msg)
        raise Exception(msg)

    if input_name in request.files:
        file_uploaded = request.files[input_name]

        if file_uploaded.filename == '':
            msg = u'Error de nombre de archivo'
            print(msg)
            raise Exception(msg)

        if file_uploaded.content_type in allowed_types:
            filename = u'{}_{}'.format(random.randint(999, 9999), secure_filename(file_uploaded.filename))
            upload = file_uploaded.save(os.path.join(upload_folder, filename))
            print(u'---------> upload: {}'.format(upload))
            return filename
        else:
            msg = u'Archivo no permitido'
            print(msg)
            raise Exception(msg)

    else:
        msg = u'Sin archivo'
        print(msg)
        raise Exception(msg)