Skip to content

Instantly share code, notes, and snippets.

@rodrigobertin
Last active September 5, 2019 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigobertin/a2536b7eb471cfe1eb94c0cf08317a06 to your computer and use it in GitHub Desktop.
Save rodrigobertin/a2536b7eb471cfe1eb94c0cf08317a06 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment