Handling File Uploads With Flask - miguelgrinberg.com

PHOTO EMBED

Tue Sep 06 2022 13:12:28 GMT+0000 (Coordinated Universal Time)

Saved by @Rmin #python #flask #uploadfile #validation

import imghdr

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')
content_copyCOPY

How you achieve content validation largely depends on the file types your application accepts. For the example application in this article I'm using images, so I can use the imghdr package from the Python standard library to validate that the header of the file is, in fact, an image. Let's write a validate_image() function that performs content validation on images:

https://blog.miguelgrinberg.com/post/handling-file-uploads-with-flask