Last active
September 5, 2019 19:35
-
-
Save rodrigobertin/a2536b7eb471cfe1eb94c0cf08317a06 to your computer and use it in GitHub Desktop.
Upload images with Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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